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.



Similar Reads

How to Deep clone in JavaScript ?
In general, cloning means copying one value to another. In JavaScript, we do cloning i.e. copying one value to another using JavaScript. To be more precise there are two types of cloning in JavaScript. As a programmer, it might be a beginner or veteran he/she should be able to know the differences between Deep clone and shallow clone. As this artic
3 min read
How to Deep Clone an Object & Preserve its Type with TypeScript ?
In TypeScript, deep cloning an object by preserving its type consists of retaining the same structure and type information as of original object. Below are the approaches to Deep Clone an Object & Preserve its Type: Table of Content Using JSON.stringify and JSON.parseUsing Object.Assign functionUsing JSON.stringify and JSON.parseIn this approac
2 min read
How do we Create a Deep Clone of a Value using Lodash?
Lodash provides the _.cloneDeep() method to create a deep copy of a value, recursively cloning nested objects and arrays. This method ensures that the newly created object has the same value as the original but they are distinct objects in memory. Syntax_.cloneDeep(originalObj)Return Value:This method returns the deep-cloned value. Run the below co
2 min read
How to Implement a Custom Promise in JavaScript ?
A custom Promise in JavaScript encapsulates asynchronous operations. It takes two parameters, resolves and rejects functions, and executes an async task. Resolve is called on success with the result, while reject is called on failure with an error. Table of Content Using Class SyntaxUsing Factory FunctionUsing Class SyntaxIn this approach, we are c
3 min read
Implement Custom Array Flat method in JavaScript
The flat() method in JavaScript is used to flatten nested arrays. By using that function we can directly convert any type of array into 1D array. These are the following approaches to implementing a custom array flat method in JavaScript: Table of Content Using Recursion approachUsing Iterative approachUsing Recursion approachThis approach uses a r
2 min read
How to add custom styles and ways to add custom styles in Tailwind-CSS ?
Tailwind is a popular CSS framework that makes your User Interface design making the process easier. It provides low-level classes and those classes combine to create styles for various components. Tailwind-CSS comes with a bunch of predefined styling but as a developer, we need more custom styling and the styles offered by tailwind are not enough
3 min read
How to implement the Tailwind CSS with Custom Angular Library ?
Tailwind CSS is basically a Utility-first CSS framework for building rapid custom UI. It is a highly customizable, low-level CSS framework that gives you all of the building blocks that you need. Also, it is a cool way to write inline styling and achieve an awesome interface without writing a single line of your own CSS. Angular is a client-side Ty
3 min read
How to clone a given regular expression in JavaScript ?
In this article, we will know How to clone a regular expression using JavaScript. We can clone a given regular expression using the constructor RegExp(). The syntax of using this constructor has been defined as follows:- Syntax: new RegExp(regExp , flags) Here regExp is the expression to be cloned and flags determine the flags of the clone. There a
2 min read
How to clone a JavaScript object ?
Cloning a JavaScript object is a task that is used mostly because we do not want to create the same object if the same object already exists. There are a few ways. By iterating through each property and copying them to the new object.Using JSON method as the source object MUST be JSON-safe. So it needs exception handling to keep it safe in the case
2 min read
Create a Paint clone using HTML CSS & JavaScript
In this article, we will see how we can create a simple paint clone using HTML, CSS, and JavaScript. Users will be able to draw, change colors, adjust brush size, erase, and clear the canvas. Preview of final output: Let us have a look at how the final output will look like Prerequisites:HTMLCSSJavsScriptApproach:Begin by setting up the HTML. We cr
4 min read