re: How to make a real copy of a JavaScript Array with Objects (without a reference) VIEW POST

VIEW PARENT COMMENT VIEW FULL DISCUSSION
 

That will work as a 'shallow copy' (in a different meaning than used above), since modifying an item from the original array will also cause a change in the equivalent item in the copied array (since those items are in fact the very same items).

 

You could use the spread-operator to create a deep copy of the Array. E.g.

const duplicateObject = originalObject.map(x => ({...x}));

That's a clean way to improve the depths of the copy, but it once again falls short when the object nesting goes down 3 levels instead of 2. To resolve that, you'd have to do a manual deep copy (in whatever succinct way).

The performance of the parse(stringify(x)) approach is notably not that bad, particularly compared to a deep copy (although the former of course copies only data, not functions). For example: jsperf.com/deep-copy-vs-json-strin...

Tests were very helpful. Although I am not intending to run the copy more than once a restart of the app. So this works for me.

code of conduct - report abuse