JS: Deep Copy Array or Object 📜
Deep Copy
Here is the best way to clone (deep copy) a object. Object can be type Array or Object.
🛑 WARNING: this method convert all undefined to null .
/* xah_deep_copy_nested_object(xobj) deep copy/clone a object. This is the best way. fastest too. WARNING: this method convert all undefined to null . http://xahlee.info/js/js_clone_object.html Version: 2017-01-30. */ const xah_deep_copy_nested_object = (xobj) => JSON.parse(JSON.stringify(xobj)); console.log( xah_deep_copy_nested_object( { a: 42, b: [7, { gwt: 560 }, 6], c: { ca: 46, cb: { cba: 50 } }, d: 21 }, ), ); /* { a: 42, b: [ 7, { gwt: 560 }, 6 ], c: { ca: 46, cb: { cba: 50 } }, d: 21 } */
Shallow Copy
For shallow copy, use the slice method with no argument.
This is same as clone if your array does not contain elements that are references (that is, other array or objects.).
const oldArray = [3,4,5]; // shallow copy const newArray = oldArray.slice();
[see Array.prototype.slice]
Difference Between Deep Copy and Shallow Copy
Shallow copy copies by reference of nested elements. This means, if you have shallow copy, changing a nested object may also change your copy.
// shallow copy nested object (including array) result in the nested reference object sharing identity, thus changing the nested item changes both const nestedItem = [8]; const xarray = [3, nestedItem]; console.log(xarray); // [ 3, [ 8 ] ] // shallow copy const xcopy = xarray.slice(); console.log(xcopy); // [ 3, [ 8 ] ] nestedItem[0] = 4; // both are changed console.log(xarray); // [ 3, [ 4 ] ] console.log(xcopy); // [ 3, [ 4 ] ]