How to Deep Clone Objects in JavaScript

Object cloning is something that we may often come across while coding. As we know, Objects and Arrays in JavaScript are reference type, if we normally copies an object or array then it will do a shallow copy, not a deep copy. If nested objects are present inside an object then deep copy is must.

If nested objects are not present, then below methods can work fine for deep cloning objects.

Using Spread(…) operator

const obj = {name: 'Amitav', age: 24};

const copyObj = {...obj};

copyObj.name = 'Denver';

console.log(obj.name); // "Amitav"

console.log(copyObj.name); // "Denver"

Using Object.assign()

const obj = {name: 'Amitav', age: 24};

const copyObj = Object.assign({}, obj);

copyObj.name = 'Denver';

console.log(obj.name); // "Amitav"

console.log(copyObj.name); // "Denver"

Deep Cloning of multi level Objects

Using recursive function

To deep clone an object, you need to iterate through each property and check if the current property contains an object. If yes, then do a recursive call to the same function by passing the current property value (i.e. the nested object). Look at the below example.

const obj = {
      name: 'Amitav', 
      age: 24,
      address: {
          city: 'Bangalore',
          state: 'Karnataka'
      }
};

const makeDeepClone = (obj) => {
    let newObject = {};

    Object.keys(obj).map(key => {
        if(typeof obj[key] === 'object'){
            newObject[key] = makeDeepClone(obj[key]);
        } else {
            newObject[key] = obj[key];
        }
  });

  return newObject;
}

const copyObj = makeDeepClone(obj);

console.log(copyObj); 
// {name: "Amitav", age: 24, address: {city: "Bangalore", state: "Karnataka"}}

copyObj.address.state = 'Odisha';

console.log(obj.address.state); // "Karnataka"

console.log(copyObj.address.state); // "Odisha"

Using JSON.stringify() and JSON.parse()

First convert your original object into string and then parse it back to JSON object from it and voila! Your new deeply cloned object is ready.

const obj = {
      name: 'Amitav', 
      age: 24,
      address: {
          city: 'Bangalore',
          state: 'Karnataka'
      }
 };

const copyObj = JSON.parse(JSON.stringify(obj));

console.log(copyObj);
// {name: "Amitav", age: 24, address: {city: "Bangalore", state: "Karnataka"}}

copyObj.address.city = 'Delhi';

console.log(obj.address.city); // " Bangalore"

console.log(copyObj.address.city); // "Delhi"

This technique (JSON.parse(JSON.stringify(obj))) doesn’t work if your object property contains function as value. Because when you JSON.stringify the object, the property containing function as value gets removed from the object. So go for recursive function approach in such case.

Well you can choose any of the procedure by keeping the object structure in mind for do deep cloning .

References

Leave a Reply

Your email address will not be published. Required fields are marked *