Object is referenced instead of cloned

Hi Forum,

I have the following code in a function node and I wonder why Node-RED behaves the way it does.

If I say "msg.debug = msg.test" and I make changes to msg.debug, msg.text will get changed the same way. Probably I am missing something here and my programming skills are too bad. Hope you guys can help me understanding this behaviour?

msg.test = {};
msg.test.t1 = "1";
msg.test.t2 = "2";
msg.debug = msg.test;
msg.debug.t1 = "11";

return msg;

msg.debug.t1 and msg.test.t1 will be set to "11" instead of just msg.debug.t1 :man_shrugging:
How can I make duplicates of an object and have it unique?

In Javascript object are stored by reference
msg.debug = msg.test; tell javascript to reference the same memory space, so now msg.debug and msg.test refer to the same memory.
Use
msg.debug = RED.util.cloneMessage(msg.test);

2 Likes

thank you very much @E1cid

I also found the official explanation but for me it was really difficult to understand:
Cloning messages in a flow : Node-RED (nodered.org)

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