When dealing with complex data structures in JavaScript, it's often helpful to create a deep copy of an array instead of a shallow reference. This ensures that changes to the cloned copy do not affect the original array and vice versa.
Using structuredClone
The modern approach to deep cloning an array is using the structuredClone method:
array2 = structuredClone(array1);
This method is supported in most modern browsers, providing a reliable deep cloning mechanism.
If structuredClone is not available, you can use a JSON-based technique:
let clonedArray = JSON.parse(JSON.stringify(nodesArray))
This approach works for objects that are JSON-serializable, meaning they can be converted to a JSON string and back. However, it may not be suitable for complex objects with functions or certain data types.
For shallow objects, using the spread operator combined with map can provide better performance:
clonedArray = nodesArray.map(a => ({...a}))
This technique creates a new object for each element in the array, ensuring that changes to the clone do not affect the original.
The best approach for cloning an array of objects depends on your specific requirements. For a reliable deep copy, structuredClone is recommended. For JSON-serializable objects, JSON.parse and JSON.stringify provide a flexible option. For shallow objects, the spread operator and map method offer better performance.
The above is the detailed content of How to Deep Clone an Array of Objects in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!