Send each item of array in a message payload separately

I have an array msg.options =[1,2,3,4,5], and i want to send each item in msg.payload.
i used this in function

for( var i = 0; i < msg.options.length; i++){ 
   msg.payload = msg.options[i]
    return msg;
}

But it always send me the first item. msg.options[0].
Any ideas will be appreciated.

You will find a code ready to use in the docs. See Multiple Messages:

I would just change the loop in the function as below (personal preference):

let SplitMsg=[];

for (let elem of msg.payload) {
    SplitMsg.push({payload:elem});
}

return [SplitMsg];
1 Like

Of just use the split node

2 Likes

FYI, your code was almost perfect, if you had used node.send...

for( var i = 0; i < msg.options.length; i++){ 
   msg.payload = msg.options[i]
   node.send(msg);
}

Nice to have options (pun intended)

good to know about" node.send". i never used it before. Thank you all.

It might be worth re-reading the docs...
https://nodered.org/docs/writing-functions#sending-messages-asynchronously

2 Likes