This post will discuss how to create a shallow and deep copy of an object array in JavaScript.

Copying an object array in JavaScript can be done in different ways, depending on whether we want to create a shallow copy or a deep copy of the array. A shallow copy means that the new array will reference the same objects as the original array, while a deep copy means that the new array will contain independent copies of the objects in the original array.

1. Creating a shallow copy

One way to create a shallow copy of an object array is to use the spread operator (…), which creates a new array with the same elements as the original array. Here’s an example:

Download  Run Code

 
Another way to create a shallow copy of an object array is to use the Array.map() function, which creates a new array with the results of calling a function on every element in the original array. Here’s an example:

Download  Run Code

 
Both of these functions will create a new array that references the same objects as the original array. This means that if we modify an object in one array, it will also affect the other array. Here’s an example:

Download  Run Code

2. Using JSON functions

If we want to create a deep copy of an object array, we need to use a function that can recursively copy all the properties and values of each object in the array. One way to do this is to use the JSON.stringify() and JSON.parse() functions, which convert an object to a JSON string and then parse it back to an object. Here’s an example:

Download  Run Code

 
This function will create a new array that contains independent copies of the objects in the original array. This means that if we modify an object in one array, it will not affect the other array. Here’s an example:

Download  Run Code

 
However, this function has some limitations, such as not being able to copy functions, symbols, or circular references. Also, it can be slower than other functions.

3. Using a custom function

Another way to create a deep copy of an object array is to use a custom function that can recursively clone each object in the array. Here’s an example:

Download  Run Code

 
This function will also create a new array that contains independent copies of the objects in the original array. However, this function can also handle functions, symbols, and circular references. Also, it can be faster than the JSON function.

4. Using structuredClone() function

We can use the structuredClone() function to deep clone any type of array in modern browsers. It creates the structured clone of an array, meaning it preserves the internal structure and references to it. This works well for arrays that contain complex objects, such as dates, maps, sets, including functions and symbols. Note, it is not widely supported by all browsers yet.

Download Code

That’s all about creating a deep copy of an object array in JavaScript.