Object Cloning
JavascriptPunchline
Copy arrays and objects safely using structuredClone():
let myArray = [1,2,3];
let myObject = {a:1, b:2, c:3};
let arrayCopy = structuredClone(myArray);
let objectCopy = structuredClone(myObject);
For details, look below:
Copying Arrays - Shallow
Structure only - Unnested case
Let's say you have a defined array:
let myArray = [1,"2text",'text',4.56];
You can copy this in the following ways:
let copy = [...myArray];
let copy = myArray.slice();
let copy = Array.from(myArray);
However, this only copies primitives (data with no methods/properties).
If you try to copy an Array with other arrays or objects inside, you only copy the reference
Example
Let's say you have a nested array:
let myArray = [1,"2text",['text', 'text2', 'text3'],{a:1,b:2}];
Using any of the shallow copying techniques causes problems:
let copy = [...myArray];
copy[2][0] = 'a' // set value of nested property
console.log(myArray);
[1,"2text",['a', 'text2', 'text3'],{a:1,b:2}]
This messes with the original!
Copying Arrays - Deep
References too
Let's say you have a defined nested array:
let myArray = [1,"2text",['text', 'text2', 'text3'],{a:1,b:2}];
You can copy this in the following ways:
let copy = structuredClone(myArray);
let copy = JSON.parse(JSON.stringify(myArray));
Be warned, the second option only copies types supported by JSON, so
undefined, Date, Map, Set, RegExp, and circular references will break it!
Copying Objects - Shallow
Structure only - Unnested case
Let's say you have a defined object:
let myObject = {a:1, b:"2text", c:'text', d:4.56};
You can copy this in the following ways:
let copy = {...myObject};
let copy = Object.assign({}, myObject);
However, this only copies primitives (data with no methods/properties).
If you try to copy an Object with other arrays or objects inside, you only copy the reference
Example
Let's say you have a nested object:
let myObject = {a:1, b:"2text", c:['text', 'text2', 'text3'], d:{a:1,b:2}};
Using any of the shallow copying techniques causes problems:
let copy = {...myObject};
copy.c[0] = 'a' // set value of nested property
console.log(myObject);
{a:1, b:"2text", c:['a', 'text2', 'text3'], d:{a:1,b:2}}
This messes with the original!
Copying Objects - Deep
References too
Let's say you have a defined nested object:
let myObject = {a:1, b:"2text", c:['text', 'text2', 'text3'], d:{a:1,b:2}};
You can copy this in the same following ways:
let copy = structuredClone(myObject);
let copy = JSON.parse(JSON.stringify(myObject));
Be warned, the second option only copies types supported by JSON, so
undefined, Date, Map, Set, RegExp, and circular references will break it!