AppDividend
Latest Code Tutorials

How To Clone Object In Javascript Tutorial With Example

0

In this tutorial, we will see How To Clone Object In Javascript. Objects are the fundamental data structure of JavaScript. The Javascript object is the collection of properties, and property is an association between the key-value pair.  JavaScript offers many ways to copy an object, but not all provide a deep copy. Copying objects in JavaScript can be tricky. Some ways perform a shallow copy, which is the default behavior in most of the cases.

Clone Object In Javascript

Before we start this example, you need to understand the difference between deep copy and shallow copy.

Shallow Copy Objects

A shallow copy successfully copies the primitive types like numbers and strings, but any object reference will not be recursively copied, but instead, the new, copied object will reference the same object. The deep copy will duplicate every object it encounters. The copy and the original object will not share anything so that it will be a copy of the original. Let’s see the example of Shallow Copy of Javascript Object.

Write the following code inside the app.js file.

// app.js

const mainObj = {
  name: 'Krunal',
  university: 'GTU',
  college: 'VVP Engineering College'
}

let objCopy = Object.assign({}, mainObj);
console.log(objCopy);

In the above code, we have used the Object.assign method. It copies all the object properties to the new one. Now, see the output below.

 

How To Clone Object In Javascript Tutorial With Example

Now, Let’s see if immutability exists. It means if we can modify the new object or not.

// app.js

const mainObj = {
  name: 'Krunal',
  university: 'GTU',
  college: 'VVP Engineering College'
}

let objCopy = Object.assign({}, mainObj);
console.log(objCopy);
console.log('.....');
objCopy.name = 'Ankit';
console.log(objCopy);
console.log('.....')
console.log(mainObj);

The output is following.

 

How To Clone Object In Javascript

In the code, we have changed the value of the property name in an objCopy object to Ankit, and when we log the modified objCopy object in the console, the changes only apply to an objCopy object. The last line of code checks that the mainObj object is still intact and hasn’t changed. So, that means, we have successfully created a clone of the source object without any references to it.

Now, let’s create another example now, and see how shallow copy has one issue.

// app.js

const mainObj = {
  name: 'Krunal',
  university: 'GTU',
  college: 'VVP Engineering College',
  result: {
    CGPA: 8.6
  }
}

let objCopy = Object.assign({}, mainObj);
console.log('New Object',objCopy);
console.log('Old Object', mainObj);

console.log('.....');
objCopy.name = 'Ankit';
console.log('New Object',objCopy);
console.log('Old Object',mainObj);

console.log('.....')
objCopy.result.CGPA = 7.0;
console.log('New Object',objCopy);
console.log('Old Object',mainObj);

Here, we have changed the CGPA from 8.6 to 7.0. Now, see what the final output of the Old and New object.

 

Shallow Copy in Javascript

Now, you can see that old and new object’s CGAP property is changed to 7. Well, that’s weird. Well, that is a pitfall of Object.assign() method. Object.assign() only makes the shallow copies. Both mainObj.result and copyObj.result share the same reference to the object because of individual clones or copies were not made. Instead, the reference to the object was cloned. Any change made to any of the object’s property applies to all references using the object.

You can also perform the shallow copy using the spread operator in Javascript. You can also write the following code instead of Object.assign() method.

const objCopy = {...mainObj};

It will give us the same shallow copy of the Javascript object.

Deep Copying Objects

The deep copy will duplicate every object it encounters. The copy and the original object will not share anything so that it will be a copy of the original. When performing a deep copy, those external objects are copied as well, so the new, cloned object is entirely independent of the old one. We can solve that problem by using Deep Copying Objects in Javascript.

Now, for performing the Deep Copy, you can use the loadash library that is very well tested. But, for that, we need to install that library. So, let’s do that.

First, create a package.json file using the following command.

npm init -y

Then install the loadash library using the following code.

npm install loadash.clonedeep  --save

We are testing the example using Node.js. So let’s import that library and use the function provided by loadash.

// app.js

const deepClone = require('lodash.clonedeep');

Now, in the above example, instead of using Object.assign method, use the deepClone method. Write the following code inside the app.js file.

// app.js

const deepClone = require('lodash.clonedeep');

const mainObj = {
  name: 'Krunal',
  university: 'GTU',
  college: 'VVP Engineering College',
  result: {
    CGPA: 8.6
  }
}

let objCopy = deepClone(mainObj);
console.log('New Object',objCopy);
console.log('Old Object', mainObj);

console.log('.....');
objCopy.name = 'Ankit';
console.log('New Object',objCopy);
console.log('Old Object',mainObj);

console.log('.....')
objCopy.result.CGPA = 7.0;
console.log('New Object',objCopy);
console.log('Old Object',mainObj);

Now, see the output.

 

Deep Copying Objects using Loadash

Now, you can see that after modifying the properties of an objCopy object, the mainObj is still intact and not changed. So this is the pure example of Deep Cloning.

Not Recommended methods to clone the Object in Javascript

The following methods are not recommended to clone the object in Javascript.

  1. Using Object.create() method.
  2. Use of JSON serialization.

Finally, How To Clone Object In Javascript Tutorial With Example is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.