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 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"]]}]

Flow Info

created 1 year, 9 months ago

Node Types

  • function (x1)
  • subflow (x1)
  • subflow:b7765500.4889a8 (x1)


  • foreach
  • for
  • iterate
  • itteration
Copy this flow JSON to your clipboard and then import into Node-RED using the Import From > Clipboard (Ctrl-I) menu option