Home >Web Front-end >JS Tutorial >How to Best Deep Copy an Array of Interconnected Objects in JavaScript?
When working with complex data structures, such as arrays of objects with references to other objects within the same array, creating a true deep copy can be challenging. Let's explore various approaches:
The modern solution for deep copying is using structuredClone():
array2 = structuredClone(array1);
This method supports a wide range of data types and is supported by most browsers.
For objects with JSON-serializable content, a simple one-line solution is:
let clonedArray = JSON.parse(JSON.stringify(nodesArray))
However, it has limitations with non-serializable content and performance issues compared to other methods.
If your array contains shallow objects, the spread operator combined with .map() can be used for a fast and efficient deep copy:
clonedArray = nodesArray.map(a => ({...a}));
This method outperforms JSON.parse significantly.
The above is the detailed content of How to Best Deep Copy an Array of Interconnected Objects in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!