Deep clone an object in JavaScript

There are three ways to deep clone (copy deep ) an object in JavaScript, let consider one by one the way below:

1 - Use assign method:

function objectClone(obj) {
  return Object.assign({}, obj);
}


2 - Use a recursion function:

function isObject(obj) {
  const type = typeof obj;
  return type === 'function' || type === 'object' && !!obj;
};

function objectClone(obj) {
  let newObj = {};
  for (let prop in obj) {
    if (obj.hasOwnProperty(prop)) {
      if (isObject(obj[prop])) {
        newObj[prop] = objectClone(obj[prop]);
      } else {
        newObj[prop] = obj[prop];
      }
    }
  }
  return newObj;
}

With this way, we created two functions, isObject function to check the type of the source and objectClone function is a recursion function to clone the object.

3 - Use JSON.parse method:

function objectClone(obj) {
  return JSON.parse(JSON.stringify(obj));
}


Example:

const obj = {a: 1, b: {c: 2, d: { e: 3 }}};
const copyObj = objectClone(obj);

obj.b.d.e = 2;
console.log(copyObj.b.d.e); // 3


clone deepclone objectcopy objectjavascript

© 2019 4codev

Created with love by Sil.