Modifying every element of an array

I know I keep asking javascript questions here, but every step you guys help me overcome reveals another problem to fix. I promise I gave it my all on this one, but I can't seem to find a way out.

I'd like to modify every element of an array the same way. So make [1,2,3,4] into [n1,n2,n3,n4]. Now the forEach() is able to do this fairly easily, but I think my problem may be more specific. What I'm trying to do is make every item in an array into an object. So [1,2,3] becomes [{"item": 1},{"item": 2},{"item": 3}].
Man, .forEach() wants to do it so bad, but I'm getting that stringified "[object Object]" thing in the debug node, and I just don't know how to parse it out. Node.send() will spit out each item individually, so I thought I might just build another array with .push()...but I'm making things goofy at that point.

Thanks in advance for the great help!

Hi .. forEach() and push() would be my approach also
i dunno exactly what you have tried but here's an example

let newArray = []
msg.payload.forEach( el => newArray.push({item: el}) )
msg.payload = newArray;
return msg;

Flow:

[{"id":"f7c2e7cb.b1fdc","type":"inject","z":"8889c53d.0c1208","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"[1,2,3,4]","payloadType":"json","x":330,"y":380,"wires":[["68b77baa.92d79c"]]},{"id":"68b77baa.92d79c","type":"function","z":"8889c53d.0c1208","name":"","func":"let newArray = []\n\nmsg.payload.forEach( el => newArray.push({item: el}) )\nmsg.payload = newArray;\n\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":520,"y":380,"wires":[["3abded27.50e27a"]]},{"id":"3abded27.50e27a","type":"debug","z":"8889c53d.0c1208","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":720,"y":380,"wires":[]}]

Thank you very much. This works great. I actually didn't even try finishing out my way with the push(), because I figured I was making extra steps. Yours is more elegant than what I was about to do, so I'm glad I asked anyways. I gotta learn those arrow functions or whatever they're called. A lot of basic things still way beyond me just yet.
Thanks again!

There is a very good tutorial on youtube by Brad Traversy that covers some examples of
forEach(), map(), sort(), filter()

the video covers both the use of normal functions and arrow function.
definitely worth watching

JavaScript Higher Order Functions & Arrays

4 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.