Open In App

Implement Custom Function to Deep clone in JavaScript

Last Updated : 16 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In general, cloning means copying one value to another. In JavaScript, there are two types of cloning, i.e. Deep clone and shallow clone. This article is about Deep clones and we will learn about Deep clones. 

Cloning is a concept that can happen in any data type i.e. it might be a primitive data type (like string, number) or composite data types like arrays and JavaScript.

Deep Clone: Deep clone is a technique that is used to duplicate everything whenever we are cloning arrays and objects in JavaScript in order to avoid data loss.

 

Example 1: As in the below example, the data is becoming corrupted if we change one object value then it is reflected in other objects also that is the reason in order to avoid this problem we use Deep Clone.

Javascript




var obj1 = {
    name: "Geeks",
    company: "Gfg"
}
  
var obj2 = obj1;
  
obj1.name = "GeeksForGeeks"
  
console.log("First name is", obj1.name)
console.log("Second name is ", obj2.name);


Output:

First name is GeeksForGeeks
Second name is  GeeksForGeeks

Example 2: As in the below example, the data is becoming corrupted if we change one object value then it is reflected in other objects also.

Javascript




var employee = {
    eid: "E102",
    ename: "Jack",
    eaddress: "New York",
    salary: 50000
}
  
var newEmployee = employee;
  
newEmployee.ename = "Beck";
console.log("New Employee", newEmployee);
console.log("Old Employee", employee);


Output:

New Employee, { 
    eid: 'E102', 
    ename: 'Beck', 
    eaddress: 'New York', 
    salary: 50000 
}
Old Employee, { 
    eid: 'E102', 
    ename: 'Beck', 
    eaddress: 'New York', 
    salary: 50000 
}

Approach: Now we will create our own custom function to deep clone an object.

  • We will make a function deepCopy which will take an object whose deep copy needs to be created as input and will return a deeply copied object.
  • We will declare a result object which will store the final output.
  • Check if the input object is:
    • Null or undefined or an array or a function or not of the type object(for example – string, boolean number), then we will simply return the input
    • If the input is of a type object then we will fetch the keys of the object using the Object.keys method and for each of the keys will again call the deepCopy function.
  • Return result.

Example: This example shows the use of the above-explained approach.

Javascript




// Declare object to be cloned
const obj = {
    name: {
        firstName: "alice",
        lastName: null
    },
    address: {
        number: 12345,
        country: "London",
        pincode: 208027
    },
    email: "foo@bar.com",
    hobbies: ["singing", "dancing", "music"],
}
  
// Declare object to be cloned
const objTwo = {
    a: null,
    b: true
}
  
  
// Function to deep copy an existing object 
// and return new object
function deepCopy(obj) {
  
    // Declare object which will store the output
    const result = {};
  
    // If the object isnt of type object or 
    // object is null, undefined, is an Array
    // or a function then no need to iterate
    // over it and simply return it
    if (typeof obj !== "object" || 
        typeof obj === undefined || 
        obj === null || 
        Array.isArray(obj) || 
        typeof obj == "function") {
        return obj;
    }
  
    // Store the keys of the object
    const keys = Object.keys(obj);
  
    // Iterate through the keys of the
    // object retrieved above
    for (let key in keys) {
      
        // Recursively iterate through each of the key.
        result[keys[key]] = deepCopy(obj[keys[key]])
    }
    return result;
}
  
const deepCopiedObject = deepCopy(obj)
  
const deepCopiedObjectTwo = deepCopy(objTwo);
  
// Modifying property country
obj.address.country = "india" 
console.log(deepCopiedObject)
console.log(obj)
  
objTwo.a = "gfg";
console.log(deepCopiedObjectTwo)
console.log(objTwo)


Output:

{
    name: { firstName: 'alice', lastName: null },
    address: { 
        number: 12345, 
        country: 'London', 
        pincode: 208027 
    },
    email: 'foo@bar.com',
    hobbies: ['singing', 'dancing', 'music']
}
{
    name: { firstName: 'alice', lastName: null },
    address: { 
        number: 12345, 
        country: 'india', 
        pincode: 208027 
    },
    email: 'foo@bar.com',
    hobbies: ['singing', 'dancing', 'music']
}
{ a: null, b: true }
{ a: 'gfg', b: true }

Explanation: Even after modifying the obj the data is safe in deepCopiedObject and deepCopiedObjectTwo and doesn’t get mutated.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads