Skip to content

Instantly share code, notes, and snippets.

@dhartveld
Last active February 17, 2016 16:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhartveld/43501a1b424434de0ffb to your computer and use it in GitHub Desktop.
Save dhartveld/43501a1b424434de0ffb to your computer and use it in GitHub Desktop.
forEach (array iteration & completion)

This subflow, creates a node with 2 outputs.

Output 1 - is called for each object in the array (the object is supplied as msg.payload) Output 2 - is called when the iteration is completed with a final output array.

Output 1 should eventually to be connected back to the node's input, where the msg.payload will be used as the final element in the output array.

If initial input is not an array it will be treated as an array with a single object.

Example Usage:

Using Iterate to multiply each number in an array by 5

[{"id":"b7765500.4889a8","type":"subflow","name":"Iterate","in":[{"x":220,"y":219,"wires":[{"id":"a1ad0c48.5e52f"}]}],"out":[{"x":454,"y":174,"wires":[{"id":"a1ad0c48.5e52f","port":0}]},{"x":455,"y":259,"wires":[{"id":"a1ad0c48.5e52f","port":1}]}]},{"id":"a1ad0c48.5e52f","type":"function","name":"Iterate","func":"//Node has 2 outputs - 1 for itteration and 1 for completion\nvar nextObj, out;\nvar itt = msg.iterationInfo;\n\n\n//If the iterating has not yet begun set up the iteration metadata in the msg\nif (typeof itt === 'undefined') {\n //Make sure payload is an array\n if( Object.prototype.toString.call(msg.payload) !== '[object Array]' ) {\n msg.payload = [msg.payload];\n }\n\n msg.iterationInfo = itt = {};\n itt.index = -1;\n itt.inArray = msg.payload;\n itt.outArray = [];\n\n//Otherwise just push the input to the output array\n} else {\n itt.outArray.push(msg.payload)\n}\n\n//Goto next object\nitt.index ++;\n\n//If there are stil objects left to iterate goto the next one in the original array\nif (itt.index < itt.inArray.length) {\n nextObj = msg;\n msg.payload = itt.inArray[itt.index];\n\n//otherwise pass the out array as the payload\n} else {\n out = msg;\n msg.payload = itt.outArray;\n delete msg.iterationInfo;\n}\n\nreturn [nextObj, out];","outputs":"2","noerr":0,"x":347,"y":220,"z":"b7765500.4889a8","wires":[[],[]]},{"id":"d031fa3c.2fce08","type":"subflow:b7765500.4889a8","name":"Iterate","x":568,"y":322,"z":"ce44b4c2.31bb48","wires":[["a5b7e659.5a4818"],["40b4c609.bf4b38"]]}]
@kadu
Copy link

kadu commented Feb 17, 2016

I'm trying to use 2 Iterate on same flow, but secound interation still with content of first payload

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment