How to Deep Copy Array in JavaScript

Subodh Poudel Feb 02, 2024
  1. Introduction to Shallow Copy and Deep Copy in JavaScript
  2. Use the structuredClone() Method to Create a Deep Copy of an Object in JavaScript
  3. Use the JSON.parse() and JSON.stringify() Methods to Create a Deep Copy of an Object in JavaScript
  4. Use the Lodash Library to Create a Deep Copy of an Object in JavaScript
How to Deep Copy Array in JavaScript

In this article, you will learn the deep and shallow copy concept. The article will also introduce ways to perform deep copy on arrays in JavaScript.

Introduction to Shallow Copy and Deep Copy in JavaScript

In JavaScript, an object can be copied in two ways. They are deep copy and shallow copy.

Firstly, let’s discuss shallow copy. A shallow copy of an object has properties that point to the same reference as the source object’s properties.

Here, the source object is the object from which the copy is made. Since the object and its shallow copy share the same references, the change made in one of them will reflect in the other object.

Let’s understand it by an example.

Consider an object student1 with the property named name and the value kevin. Next, create another variable, student2, and assign it with the value of student2.

let student1 = {name: 'kevin'}

let student2 = student1

Here, we just made a shallow copy of the student1 object. Now, let’s try to change the value of the name property to something else from the student2 object.

For example, the new value is john. When we print both objects student1 and student2, the value is the same: john.

Example Code:

let student1 = {name: 'kevin'}

let student2 = student1

 student2.name = "john"

console.log(student1)
console.log(student2)

Output:

{
  name: "john"
}
{
  name: "john"
}

This is how a shallow copy of an object behaves. It can change the source object’s properties as both objects share the same references.

However, the deep copy of an object acts quite the opposite. As the copy and the source object do not point to the same reference, changing one of the object’s properties does not change the others.

In the sections below, you will learn about deep copy and ways to achieve it in JavaScript.

Use the structuredClone() Method to Create a Deep Copy of an Object in JavaScript

One of the ways of creating a deep copy of an object in JavaScript is using the structuredClone() method. The method uses a structured clone algorithm that deep clones an object.

The method takes the object which is to be cloned as the parameter. Let’s perform the cloning.

For example, consider the student1 object above that contains the value kevin for the name property. Next, use the structuredClone() method and supply the student1 object as its parameter.

Finally, assign the method to a variable student2. This makes the student2 object a deep copy of the student1 object.

Next, change the property of the student2 object to john.

This time when you print both objects, they don’t have the same values for the properties. The student1 object will have the value kevin, and student2 will have john for the name property.

Example Code:

let student1 = {
  name: 'kevin',

}

let student2 = structuredClone(student1)

student2.name = 'john'

console.log(student1)
console.log(student2)

Output:

{
  name: "kevin"
}
{
  name: "john"
}

This is how we can use the structuredClone() method to perform the deep copy in JavaScript.

Use the JSON.parse() and JSON.stringify() Methods to Create a Deep Copy of an Object in JavaScript

We can also create a deep copy of an object using the JSON.parse() and JSON.stringify() methods. The JSON.stringify() method converts the object or a value to a string, while the JSON.parse() method creates an object or a value by parsing the JSON string.

First, we can convert the object to a string using the JSON.stringify() method, and then we can use the JSON.parse() method to create a deep copy of the object by parsing the object.

For example, consider the same student1 object and use the JSON.stringify() method to convert the object to a string. Then, use the JSON.parse() method on the result.

Assign the expression to a variable student2. Next, change the property of the first object as we did above and print both objects.

Example Code:

let student1 = {
  name: 'kevin',

}


let student2 = JSON.parse(JSON.stringify(student1))

student2.name = 'john'

console.log(student1)
console.log(student2)

Output:

{
  name: "kevin"
}
{
  name: "john"
}

We can see that the values of the properties of these two objects are different, which means that we created a deep copy of the source object. Thus, we can use the JSON.parse() and JSON.stringify() methods to perform the deep copy of an object in JavaScript.

But, we will have a problem when working with functions and objects. Let’s implement the deep clone of an object that contains a function and a Date() object to see a clearer picture of the problem.

Add the new fields to the student1 object as in the example below.

Example Code:

let student1 = {
  name: 'kevin',
  age: function() {
    return 24;
  },
  enrolledDate: new Date()

}

Next, create a deep copy of the object as above using the JSON.parse() along with the JSON.stringify() functions. Then, change the name property of the first object. Finally, print both objects.

Example Code:

let student2 = JSON.parse(JSON.stringify(student1))
student2.name = 'john'

console.log(student1)
console.log(student2)

Output:

{
  name: 'kevin',
  age: [Function: age],
  enrolledDate: 2023-01-19T16:15:30.914Z
}
{ name: 'john', enrolledDate: '2023-01-19T16:15:30.914Z' }

Here, we can see some noticeable problems in the deep copy of the object. The first problem is that the function is missing the cloned object.

The other problem is the change in the type of the nested object new Date(). After cloning, the new Date() object is changed into a type String. You can notice the quotes around the date.

Thus, we discovered a problem during the deep copy of an object that contains a function and a type when using the JSON.parse() and JSON.stringify() methods. We will resolve the problem in the next section of the article.

Use the Lodash Library to Create a Deep Copy of an Object in JavaScript

We can overcome the problem while cloning the functions and nested objects using the lodash library. lodash provides a method cloneDeep(), which takes the source object as a parameter and deep clones it.

You can install the library with the following command.

npm i -g lodash

For example, require the library at the top of your code. Assign it to a constant _.

Use the constant to invoke the cloneDeep() where the student1 object is the parameter. Change the value of the object’s property as before. Finally, print both objects.

Example Code:

const _ = require('lodash')
let student1 = {
  name: 'kevin',
  age: function() {
    return 24;
  },
  enrolledDate: new Date()

}


let student2 = _.cloneDeep(student1)

student2.name = 'john'

console.log(student1)
console.log(student2)

Output:

{
  name: 'kevin',
  age: [Function: age],
  enrolledDate: 2023-01-23T15:02:56.059Z
}
{
  name: 'john',
  age: [Function: age],
  enrolledDate: 2023-01-23T15:02:56.059Z
}

Finally, we can deep-clone the object and still have the functions and nested objects. Thus, we can use the lodash library to create a deep clone of an object in JavaScript.

Subodh Poudel avatar Subodh Poudel avatar

Subodh is a proactive software engineer, specialized in fintech industry and a writer who loves to express his software development learnings and set of skills through blogs and articles.

LinkedIn

Related Article - JavaScript Array