Converting Object to Array

Hi,

I have a msg.payload: Object as shown below:

image

I would like to convert it to an array with the following format:

Any ideas on how to achieve this? I was thinking of a function node, but do not know where to start

I am a complete newbie to Node-RED and coding so any help would be appreciated

Thanks!

Object.entries and Array.map can do this...

msg.payload = Object.entries(msg.payload).map(([key, value]) => { return {[key]:value}} )
return msg;

1 Like

You can also use a join and split node, for a low code option.
Also you can use jsonata in a change node.
here is a n example of both methods.

[{"id":"f60a5489.434a28","type":"change","z":"bf9e1e33.030598","name":"","rules":[{"t":"set","p":"payload","pt":"msg","to":"$spread(msg.payload)","tot":"jsonata"}],"action":"","property":"","from":"","to":"","reg":false,"x":350,"y":1580,"wires":[["d3e1018c.b2864"]]},{"id":"af64afa4.30bb3","type":"inject","z":"bf9e1e33.030598","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"{\"one\":1,\"two\":2}","payloadType":"json","x":160,"y":1500,"wires":[["2f53cb88.fb56c4","f60a5489.434a28"]]},{"id":"d3e1018c.b2864","type":"debug","z":"bf9e1e33.030598","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":670,"y":1580,"wires":[]},{"id":"2f53cb88.fb56c4","type":"split","z":"bf9e1e33.030598","name":"","splt":"\\n","spltType":"str","arraySplt":1,"arraySpltType":"len","stream":false,"addname":"topic","x":310,"y":1500,"wires":[["d74eb6af.1c5d38"]]},{"id":"447566c0.b6d668","type":"join","z":"bf9e1e33.030598","name":"","mode":"auto","build":"string","property":"payload","propertyType":"msg","key":"topic","joiner":"\\n","joinerType":"str","accumulate":"false","timeout":"","count":"","reduceRight":false,"x":610,"y":1500,"wires":[["d3e1018c.b2864"]]},{"id":"d74eb6af.1c5d38","type":"change","z":"bf9e1e33.030598","name":"","rules":[{"t":"move","p":"payload","pt":"msg","to":"payload[msg.topic]","tot":"msg"},{"t":"set","p":"parts.type","pt":"msg","to":"array","tot":"str"}],"action":"","property":"","from":"","to":"","reg":false,"x":450,"y":1500,"wires":[["447566c0.b6d668"]]}]

JSONata expression in a change node

$spread($$.payload)
1 Like

Thank you very much just what I was looking for!

Please mark the solution you chose (for future readers benefit). Ta.

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