The Challenge
Creating a deep copy of an array of objects that contain references to other objects within the array can be a complex task in JavaScript. Simply cloning the array only copies the references, leading to changes in one array affecting the other.
structuredClone: A Modern Solution
The most recent and preferred method for deep cloning an array in JavaScript is to use structuredClone:
array2 = structuredClone(array1);
This function is available in modern browsers (Chrome 98, Firefox 94) but requires a polyfill for broader compatibility.
JSON-based Deep Cloning
For broad browser support, JSON-based techniques can be employed.
Using JSON.parse and JSON.stringify
If your objects are JSON-serializable, you can use JSON.parse and JSON.stringify for deep cloning. However, this method has advantages and disadvantages:
Advantages
Disadvantages
let clonedArray = JSON.parse(JSON.stringify(nodesArray));
Using the Spread Operator with .map
For shallow cloning in modern browsers, the spread operator combined with .map can be more performant:
clonedArray = nodesArray.map(a => {return {...a}});
Advantages
Disadvantages
Benchmark: The spread method performs significantly faster than JSON-based cloning for an array of 20 objects with a nesting depth of 2.
The above is the detailed content of How to Deep Clone Arrays of Objects in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!