Unexpected setting of context data in Function Node

Hi,
I'm new here (and new is NodeRED form me) so I don't know if my question is really a problem;
In a function node I placed this code:

var obj = flow.get("obj");
obj[0].a = "1";
return msg;

The problem is that the flow data change olso if in this function there isn't a flow.set(...) stantment

The flow variable 'obj' is created by an another function with this code:

var obj = [{a: "str1", b: 1, c: "11:00", d: "12:00"},
            {a: "str2", b: 2, c: "13:00", d: "14:00"},
            {a: "str3", b: 3, c: "15:00", d: "16:00"}]

flow.set("obj", obj);
msg.payload = obj;
return msg;

Anyone can explain me the reasons?

I thank those who will answer me in advance

Alan

Objects in javascript are passed by reference when you get the object from flow or global context it is exactly the same object (your variable is simply a reference to the original)

Hi Steve,
thank for the fast reply :grinning:
Is there a solution to avoid this?

Alan

It depends what you are trying to achieve.

If you wish to have a new clone that doesn't affect the object, there is a helper function RED.util.cloneMessage() you can use to make a copy before modifying it.

e.g...

var obj = RED.util.cloneMessage(flow.get("obj") || {});

Thank Steve,
in the meantime I found (and tried) this code:

var objTemp = JSON.parse(JSON.stringify(obj));

is also good as is or there are some important differences?

Alan

The helper function takes care of special cases. Also, i don't think the serialisation to string is performed in the helper function so should be faster / safer.

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