Skip to content

Instantly share code, notes, and snippets.

@coderofsalvation
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coderofsalvation/47323c946caa06cf3c7e to your computer and use it in GitHub Desktop.
Save coderofsalvation/47323c946caa06cf3c7e to your computer and use it in GitHub Desktop.
for-loop (simple iterating over an array)

UPDATE: there's now a node for this @ https://www.npmjs.org/package/node-red-contrib-splitter

An array iterator. This is a 'drop-in'-flow consisting of 2 machines, which allows easy iteration over an array, and converts them to separate payloads:

Just send the following payload to the 'for each item'-machine:

[{"foo":1},{"bar":2}];

and connect the output of the 'for each item'-machine to a debug-console. By doing so, 2 separate payloads will arrive:

payload: {"foo":1}
payload: {"foo":2}

you can modify the loop behavior (break e.g.) by editing the condition in the '++' machine

this method is similar like this and this approach. However, this variation focuses on portability and simplicity.

[{"id":"3367e45f.cc981c","type":"function","name":"++","func":"if ( (msg.i += 1) < msg.items.length ) return msg;\n","outputs":1,"x":376,"y":268,"z":"886b17b1.7794e8","wires":[["116d5bb3.ee92a4"]]},{"id":"116d5bb3.ee92a4","type":"function","name":"for each item","func":"if( msg.i == undefined ) msg.i = 0;\nif( msg.items == undefined ) msg.items = msg.payload;\n\nmsg.payload = msg.items[ msg.i ];\n\nreturn msg;","outputs":1,"x":378,"y":240,"z":"886b17b1.7794e8","wires":[["3367e45f.cc981c","92f7e57c.6d0818"]]}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment