How to add key/value of json object by node change

Hi,
I would like to add key/value to the json object, I have done it using the function node.

objJsonChangeNode

[{"id":"828012fb.ba609","type":"tab","label":"フロー 1","disabled":false,"info":""},{"id":"b7825fef.5e89","type":"inject","z":"828012fb.ba609","name":"","topic":"","payload":"","payloadType":"str","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":370,"y":260,"wires":[["d20aed86.d3124"]]},{"id":"864f5526.8351b8","type":"function","z":"828012fb.ba609","name":"get data","func":"var arrVal = [];\narrVal.push('111');\narrVal.push('222');\narrVal.push('333');\nmsg.arrVal = arrVal;\n\nmsg.key = 'Data.txt';\nreturn msg;","outputs":1,"noerr":0,"x":680,"y":260,"wires":[["f517bb09.3554e8","d0c6dad4.d1bf48"]]},{"id":"d20aed86.d3124","type":"change","z":"828012fb.ba609","name":"","rules":[{"t":"set","p":"objFiles","pt":"msg","to":"{}","tot":"json"}],"action":"","property":"","from":"","to":"","reg":false,"x":520,"y":260,"wires":[["864f5526.8351b8"]]},{"id":"f517bb09.3554e8","type":"function","z":"828012fb.ba609","name":"store data","func":"msg.objFiles[msg.key] = msg.arrVal;\nreturn msg;","outputs":1,"noerr":0,"x":860,"y":220,"wires":[["671a7728.0305e8"]]},{"id":"671a7728.0305e8","type":"debug","z":"828012fb.ba609","name":"objFiles","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"objFiles","targetType":"msg","x":1000,"y":220,"wires":[]},{"id":"d0c6dad4.d1bf48","type":"change","z":"828012fb.ba609","name":"store data","rules":[],"action":"","property":"","from":"","to":"","reg":false,"x":860,"y":320,"wires":[[]]}]

Is this possible using change node?
Please tell me!
Thanks!

Sure

[{"id":"d0c6dad4.d1bf48","type":"change","z":"828012fb.ba609","name":"store data","rules":[{"t":"set","p":"objFiles","pt":"msg","to":"{key: arrVal}\t","tot":"jsonata"}],"action":"","property":"","from":"","to":"","reg":false,"x":860,"y":320,"wires":[["671a7728.0305e8"]]}]
1 Like

An important clarification to the solution provided by @E1cid is that it will replace the whole msg.objFiles object with one containing just the one key/value pair.

In the context for the example flow you've provided, that is fine and also means you can get rid of the first Function node what initialises msg.objFiles to an empty object.

In the more general case, as you ask how to add a key/value property to a message property, that currently requires a bit more complex JSONata expression:

$merge([$.objFiles,{$.key: $.arrVal}])

In the 1.3 release, you'd be able to do this without JSONata by setting the msg. type to: msg.objFiles[msg.key]

1 Like

@E1cid, @knolleary Thank your for your support!

Great!!!
Maybe jsonata can do it all @@

One useful information I will keep in mind.
Thank you!

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