How to Make Shallow & Deep Clone of a JavaScript Object

In this tutorial you will learn how to make shallow and deep clone of an object in JavaScript with code examples.

Shallow Clone vs Deep Clone:

Object cloning refers to the process of creating a duplicate of an existing object. Cloning can be shallow or deep, depending on whether nested objects are also copied. Shallow cloning creates a new object with references to the same nested objects, while deep cloning creates entirely new copies of nested objects.

Making Shallow clone of a JavaScript Object

A shallow clone creates a new object and copies all enumerable properties of the original object to the new one. However, if the properties of the original object are themselves objects, only their references are copied, not the objects themselves.

For shallow cloning you can use Object.assign() method or Spread Operator (…). Here are the code examples:

1. Using Object.assign(): Object.assign() copies enumerable own properties from one or more source objects to a target object. However, it only performs a shallow copy.

// Original object with a nested user object and a sayHi method
const originalObj = {
    user: {
        name: 'Rahul',
        age: 24,
    },
    sayHi: function () {
        console.log(this.name);
    },
};

// Shallow clone of the original object using Object.assign
const clonedObj = Object.assign({}, originalObj);

// Modifying the name property of the nested user object in the cloned object
clonedObj.user.name = 'John';

console.log(originalObj);
console.log(clonedObj);
{ user: { name: 'John', age: 24 }, sayHi: [Function: sayHi] }
{ user: { name: 'John', age: 24 }, sayHi: [Function: sayHi] }

2. Using Spread Operator (…): The spread operator offers a concise syntax for creating shallow copies of objects. It spreads the properties of the original object into a new object.

// Original object with a nested user object and a sayHi method
const originalObj = {
    user: {
        name: 'Rahul',
        age: 24,
    },
    sayHi: function () {
        console.log(this.name);
    },
};

// Shallow clone of the original object using spread operator
const clonedObj = { ...originalObj };

// Modifying the name property of the nested user object in the cloned object
clonedObj.user.name = 'John';

console.log(originalObj);
console.log(clonedObj);

Deep Clone of a JavaScript Object:

To deep clone an object in JavaScript, you need to ensure that not only the top-level properties are copied, but also any nested objects within it. This means recursively traversing the original object and creating copies of its nested objects. Here’s how you can achieve deep cloning:

1. Using JSON.parse() and JSON.stringify(): JSON.stringify() serializes an object into a JSON string, and JSON.parse() parses the JSON string back into an object. This approach effectively performs deep cloning, but it has limitations with certain data types such as functions and undefined values.

// Original object with a nested user object and a sayHi method
const originalObj = {
    user: {
        name: 'Rahul',
        age: 24,
    },
    sayHi: function () {
        console.log(this.name);
    },
};

// Deep clone of the original object using JSON methods
const clonedObj = JSON.parse(JSON.stringify(originalObj));

// Modifying the name property of the nested user object in the cloned object
clonedObj.user.name = 'John';

console.log(originalObj);
console.log(clonedObj);

2. Recursive Deep Clone: A recursive deep clone function traverses the entire object hierarchy, creating new copies of nested objects and arrays. This method is more robust than JSON-based cloning but can be less performant for very large objects.

// Original object with a nested user object containing properties and an array
const originalObj = {
    user: {
        name: 'Rahul',
        age: 24,
        item: [1, [1, 2, 3], 3],
    },
    sayHi: function () {
        console.log(this.name);
    },
};

function deepClone(obj) {
    if (obj === null || typeof obj !== 'object') {
        return obj;
    }
    const cloned = Array.isArray(obj) ? [] : {};
    for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
            cloned[key] = deepClone(obj[key]);
        }
    }
    return cloned;
}

const clonedObj = deepClone(originalObj);

// Modifying the nested array in the cloned object
clonedObj.user.item[1].push(5);

// Logging the nested array in both original and cloned objects
console.log(originalObj.user.item); // Output: [1, [1, 2, 3], 3]
console.log(clonedObj.user.item); // Output: [1, [1, 2, 3, 5], 3]

Choose the Best Method:

  • Use shallow cloning for simple objects or when maintaining references to nested objects is acceptable.
  • Prefer deep cloning when you need to create independent copies of nested objects or arrays.
  • Consider the limitations and performance implications of each cloning method, especially for large or complex objects.

Leave a Reply

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

We use cookies to ensure that we give you the best experience on our website. Privacy Policy