Table of contents
1.
Introduction
2.
Using Lodash library
3.
Iterating through each object property and copying it into a new empty object
4.
Cloning Objects using JSON.parse/stringify
5.
Custom routine
6.
Frequently Asked Questions
6.1.
What is the difference between shallow and deep copy?
6.2.
Why do we need a shallow copy?
6.3.
What is the advantage of deep cloning?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Implement Custom Deep Clone Method

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

When planning to work in Javascript, a deep knowledge of objects is necessary. It is crucial to understand how to clone an object in Javascript correctly. Copies of objects can be created in the form of shallow copies and deep copies. Now let us know what those mean. 

What is a shallow copy?

When we make a shallow copy, its object references the original. Therefore, any changes made to the original object will be reflected in the copy.

What is a deep copy?

In comparison to it, a deep clone generates a copy of all the elements from the original object. Therefore, any changes made to the original object will not be reflected in the copy. In this article, we will learn to create deep copies of objects using different build-in and custom methods.

Using Lodash library

Lodash is a library that gives two different functions that allow you to do shallow copies and deep copies. These are clone and clonedeep. To use Lodash clone methods in Node.js, one can install it by running npm i lodash.clone for the shallow clone and npm i lodash.clonedeep for a deep clone.

Code:

const cloneDeep = require('lodash.clonedeep')
let objC = {
    a: 1,
    b: {
        c: 2,
        d: {
            e: 3
        }
    }
}

// copy objC save as new variable objD
let objD = cloneDeep(objC)

// change the values in the original object objC
objC.a = 20
objC.b.c = 30
objC.b.d.e = 40

console.log(JSON.stringify(objC))
// gives output → {"a":20,"b":{"c":30,"d":{"e":40}}}

// objD which is the cloned object is still the same
console.log(JSON.stringify(objD))
// gives output → {"a":1,"b":{"c":2,"d":{"e":3}}}
You can also try this code with Online Javascript Compiler
Run Code

 

Output:

Iterating through each object property and copying it into a new empty object

Here, we create a new empty object and replicate the structure of the source object’s property by iterating through its properties and copying all of them one after the other to a target object. 

Code:

let original = {
    name: "Alex",
    age: 20
};
 
let clone = {}; // the new empty object
 
// let's copy all user properties into it
for (let key in original) {
  if (original.hasOwnProperty(key)) {
  clone[key] = original[key];
  }
}
console.log(clone.name); //clone name is same as original
console.log(original.name); // still Alex in the original object

clone.name = "Jane"; // changed the data
console.log(clone.name); // clone name changed
You can also try this code with Online Javascript Compiler
Run Code

 

Output:

Cloning Objects using JSON.parse/stringify

This offers a speedy technique for deep cloning objects. The only disadvantage is that it is not very reliable and standard as it comes with some data loss.

The JSON.stringify()  converts a JavaScript object into a JSON string while JSON.parse() converts a JSON string into JavaScript Object. By wrapping JSON.parse() around JSON.stringify() we, first convert JavaScript object into JSON String then we parse it to get a copy of the object.

Code:

const a = {
    string: 'string',
    number: 123,
    bool: false,
    nul: null,
    date: new Date(),  // string
    undef: undefined,  // lost
    inf: Infinity,  // 'null'  
}
 
console.log(typeof a.date) // returns  object
const clone = JSON.parse(JSON.stringify(a))
console.log(typeof clone.date)  // returns string
console.log(clone)
You can also try this code with Online Javascript Compiler
Run Code

 

Output:

Custom routine

In pure JavaScript, we can write a custom recursive routine for deep copying an object. The following code can be used as a starting point for this method:

Code:

deepClone = function(obj) {
    if (obj == null || typeof obj !== 'object') {
        return obj;
    }
  
    if (obj instanceof String) { return new String(obj); }
    if (obj instanceof Date) { return new Date(obj); }
    if (obj instanceof Number) { return new Number(obj); }
    if (obj instanceof RegExp) { return new RegExp(obj); }
    if (obj instanceof Boolean) { return new Boolean(obj); }
 
    // handle other objects if required
 
    var clone = {};
    if (obj instanceof Array) {
        clone = new Array(obj.length);
    }
 
    for (var key in obj) {
        clone[key] = deepClone(obj[key]);
    }
 
    return clone;
};
 
const obj =
{
    string: 'primitive string',
    stringObj: new String('string object'),
    number: 100,
    numberObj: new Number(100),
    bigInt: BigInt("9007199254740991"),
    nan: NaN,
    array: [1, 2, 3],
    arrayObj: new Array(2),
    bool: false,
    boolobj: new Boolean(false),
    nul: null,
    date: new Date(),
    undef: undefined,
    inf: Infinity,
    regExp: /(\w+)\s(\w+)/
}
 
console.log(deepClone(obj));
You can also try this code with Online Javascript Compiler
Run Code

 

Output:

Frequently Asked Questions

What is the difference between shallow and deep copy?

A Deep copy stores the copy of the original object. It recursively copies the objects as well, while a shallow Copy stores the copy of the original object and points the references to the objects.

Why do we need a shallow copy?

Shallow copies are required when we want to make copies of classes that share one sizeable underlying set of data or data structure.

What is the advantage of deep cloning?

With deep copy, the entire object is copied, including members and members of members. This may be a more time and memory-consuming process, but we can change the copy while the original remains unaffected.

Conclusion

This article helped you to understand the difference between shallow and deep clones. We also learned about creating deep copies using the lodash library, using JSON.parse/stringify function, iterating through each object, and also following custom routines.

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available, interview puzzles, look at the interview experiences, and interview bundle for placement preparations.

Check out this problem - Count Ways To Reach The Nth Stair 

We hope that this blog has helped you enhance your knowledge regarding Javascript, and if you liked this blog, check other links. Do upvote our blog to help other ninjas grow. Happy Coding!"

Live masterclass