ArticleZip > How To Deep Clone In Javascript

How To Deep Clone In Javascript

Deep cloning in JavaScript is a handy technique that allows you to create an independent copy of an object or array. Instead of referencing the original object, a deep clone ensures that any modifications made to the new copy do not affect the original data. This can be particularly useful when you need to work with complex data structures or want to maintain data integrity.

To deep clone an object or array in JavaScript, there are various approaches you can take. One common method is using the JSON.stringify() and JSON.parse() functions. Here's a simple example to demonstrate this technique:

Javascript

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

const originalObject = { a: 1, b: { c: 2 } };
const clonedObject = deepClone(originalObject);

clonedObject.b.c = 3;

console.log(originalObject); // { a: 1, b: { c: 2 } }
console.log(clonedObject); // { a: 1, b: { c: 3 } }

In this example, the deepClone function takes an object as input and returns a deep-cloned copy using JSON.stringify() to serialize the object into a JSON string representation and then JSON.parse() to deserialize it back into a new object.

While using JSON.stringify() and JSON.parse() is a straightforward approach, it has limitations. For instance, it cannot clone functions, undefined values, or circular references. If you need to handle such cases, you may consider using a more robust cloning library like Lodash or implementing a custom deep clone function.

Here's an example of a custom deep clone function that can handle more complex scenarios:

Javascript

function deepClone(obj, cloned = new WeakMap()) {
  if (obj === null || typeof obj !== 'object') {
    return obj;
  }

  if (cloned.has(obj)) {
    return cloned.get(obj);
  }

  let newObj = Array.isArray(obj) ? [] : {};

  cloned.set(obj, newObj);

  for (let key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      newObj[key] = deepClone(obj[key], cloned);
    }
  }

  return newObj;
}

const originalArray = [1, 2, [3, 4]];
const clonedArray = deepClone(originalArray);

clonedArray[2][0] = 5;

console.log(originalArray); // [1, 2, [3, 4]]
console.log(clonedArray); // [1, 2, [5, 4]]

In this custom deepClone function, we utilize a WeakMap to keep track of already cloned objects and handle circular references safely. By recursively traversing the object properties, we create a deep clone that maintains the structure and values of the original data.

Whether you choose to use a simple JSON-based approach or a more sophisticated custom function, understanding how to deep clone objects in JavaScript is a valuable skill for working with complex data structures and ensuring data integrity in your applications. By implementing deep cloning techniques effectively, you can avoid unexpected side effects and confidently manipulate data without impacting the original source.