Home > Web Front-end > JS Tutorial > How to Deep Clone Arrays of Objects in JavaScript?

How to Deep Clone Arrays of Objects in JavaScript?

Mary-Kate Olsen
Release: 2024-12-21 19:13:17
Original
345 people have browsed it

How to Deep Clone Arrays of Objects in JavaScript?

Cloning Arrays of Objects in JavaScript: An In-depth Exploration

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);
Copy after login

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

  • Clones both the array and its contents.
  • Simple one-line solution.

Disadvantages

  • Only works on JSON-serializable objects.
  • Performance is slower than using the spread operator.
let clonedArray = JSON.parse(JSON.stringify(nodesArray));
Copy after login

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}});
Copy after login

Advantages

  • Faster than JSON-based cloning.
  • Works on all types of objects.

Disadvantages

  • Only performs a shallow clone (clones the first level of the object).

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template