Implement Custom Function to Deep clone in JavaScript
Last Updated :
16 Mar, 2023
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: "[email protected]",
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: '[email protected]',
hobbies: ['singing', 'dancing', 'music']
}
{
name: { firstName: 'alice', lastName: null },
address: {
number: 12345,
country: 'india',
pincode: 208027
},
email: '[email protected]',
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? Deep clone in JavaScript refers to creating a complete copy of an object, including all nested objects, ensuring that changes to the cloned object do not affect the original. Unlike shallow cloning, deep cloning requires copying all levels of the objectâs structure.1. Using Spread Operator to Deep C
2 min read
Copy Constructor in JavaScript JavaScript does not have a built-in concept of a "copy constructor" like some other programming languages do. However, you can achieve the same result by using techniques for deep and shallow copying. In JavaScript, when you create an object, it is possible to make copies of that object. Shallow Cop
4 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 a
2 min read
How to Deep-Freeze an Object in JavaScript? In JavaScript, freezing an object prevents it from being modified. This means you can no longer add, remove, or modify the properties of an object. However, by default, JavaScript's Object.freeze() only freezes the top level of an object, leaving nested objects or arrays mutable. To achieve immutabi
4 min read
How to clone an array in JavaScript ? In JavaScript, cloning an array means creating a new array with the same elements as the original array without modifying the original array.Here are some common use cases for cloning an array:Table of ContentUsing the Array.slice() MethodUsing the spread OperatorUsing the Array.from() MethodUsing t
6 min read
What is shallow copy and deep copy in JavaScript ? JavaScript is a high-level, dynamically typed client-side scripting language. JavaScript adds functionality to static HTML pages. Like most other programming languages JavaScript allows supports the concept of deep copy and shallow copy. Shallow CopyA shallow copy occurs when you copy the reference
4 min read
Destructuring in JavaScript Destructuring Assignment is a JavaScript expression that allows to unpack of values from arrays, or properties from objects, into distinct variables data can be extracted from arrays, objects, and nested objects, and assigned to variables.Array DestructuringArray members can be unpacked into differe
3 min read
Fastest way to duplicate an array in JavaScript Multiple methods can be used to duplicate an array in JavaScript.The fastest way to duplicate an array in JavaScript is by using the slice() Method. Let us discuss some methods and then compare the speed of execution. The methods to copy an array are: Table of Content Using slice() Using concat() me
4 min read
D3.js selection.clone() Function The selection.clone() function is used to clone the selected elements and inserts these clones immediately after the same elements. Syntax: selection.clone([deep]); Parameters: This function accepts single parameters as mentioned above and described below: deep: If deep is true the descendant nodes
3 min read
How to use React.cloneElement() function? We can use React.cloneElement() method when a parent component wants to add or modify the props of its children. The React.cloneElement() function creates a clone of a given element, and we can also pass props and children in the function. The resultant element would have the initial element's props
2 min read