How do I make a copy of a global object without changing it?


macOS High Sierra 10.13.6
Node-RED version: v0.20.5
Node.js version: v10.15.3
Darwin 17.7.0 x64 LE

I seem to have run into an issue using a global where I'm not using a copy of it, but a pointer. I do this:

var arr1 = global.get('foo')||[];
var rows=arr1;

and when I make changes rows the global is changed. Attached is a very simple set of flows that shows the problem. My question is how do I make a copy of the object so I don't change the original?

globalpointer.json (2.6 KB)




Hi Paul, perhaps a shallow copy of the array ? Please have a look in this post.

1 Like



var arr1 = global.get('foo')||[];
var rows=[...arr1];

Note however, if the items in the array are objects and you change a property e.g. arr1[0].prop = 7 you will have the same issue.

This is normal JavaScript behaviour.

However adding and removing elements to the copy array won't change the original array.

If you are storing objects in the array and need copys of them in your copy array too, have a look on internet for "JavaScript copy object" then loop though or call .map() and make copies of the elements.

1 Like


@Andrei Thank you for the link pointing to

For anyone reading this thread who doesn't understand a shallow vrs deep copy of an object, go watch this video. The author does a great job of explaining it!