Summary: In this tutorial you will learn different ways to deep clone an object in JavaScript with the help of the examples.

Here are a few ways you can deep clone an object in JavaScript:

1. Using the JSON.parse() and JSON.stringify() methods

This method involves converting the object to a JSON string using JSON.stringify(), and then parsing the string back into an object using JSON.parse(). This creates a new object that is a deep clone of the original object.

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

This method is simple and easy to understand, but it has the limitation that it only works for cloning objects that have stringifiable data. This means that you can’t use it to clone functions, symbols, or other non-stringifiable data.

2. Using the lodash library’s _.cloneDeep() method

This method involves using the _.cloneDeep() method from the lodash library to create a deep clone of the object.

const _ = require('lodash');

function deepClone(obj) {
  return _.cloneDeep(obj);
}

This method is also simple and easy to understand, but it requires installing the lodash library.

3. Using the recursive function

This method involves creating a function that recursively clones the object. It does this by checking the type of the object, and then using a different approach to clone the object based on its type.

function deepClone(obj) {
  if (obj === null || typeof obj !== 'object') {
    return obj;
  }
  let copy;
  if (obj instanceof Date) {
    copy = new Date();
    copy.setTime(obj.getTime());
    return copy;
  }
  if (obj instanceof Array) {
    copy = [];
    for (let i = 0, len = obj.length; i < len; i++) {
      copy[i] = deepClone(obj[i]);
    }
    return copy;
  }
  if (obj instanceof Object) {
    copy = {};
    for (const attr in obj) {
      if (obj.hasOwnProperty(attr)) {
        copy[attr] = deepClone(obj[attr]);
      }
    }
    return copy;
  }
  throw new Error("Unable to copy obj! Its type isn't supported.");
}

This method is a bit more complex, but it allows you to specify custom handling for certain types of data (e.g. dates).

For example, the code above includes special handling for cloning Date objects, which is not possible using the first two methods.

These are just a few options, and each has its own pros and cons. The first option using JSON.parse() and JSON.stringify() is simple and easy to understand, but it only works for cloning objects that have stringifiable data.

The second option using _.cloneDeep() from the lodash library is also simple and easy to understand, but it requires installing the lodash library.

The third option using the recursive function is a bit more complex, but it allows you to specify custom handling for certain types of data (e.g. dates).

Adarsh Kumar

I am an engineer by education and writer by passion. I started this blog to share my little programming wisdom with other programmers out there. Hope it helps you.

Leave a Reply