How can I deep-clone an object in JavaScript?
Benjamin C
benjamin c profile pic

To deep-clone an object in JavaScript, you can use various methods such as recursion or theJSON.parse() andJSON.stringify() methods. Here's a step-by-step guide on how to achieve this: 1. Define the object you want to clone:

1
2
3
4
5
6
7
8
9
10

   const originalObject = {
     name: 'John',
     age: 30,
     address: {
       city: 'New York',
       country: 'USA'
     }
   };
   

Replace the properties and values with your own object structure. 2. Using recursion:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

   function deepClone(obj) {
     if (obj === null || typeof obj !== 'object') {
       return obj;
     }
     
     const clonedObj = Array.isArray(obj) ? [] : {};

     for (const key in obj) {
       clonedObj[key] = deepClone(obj[key]);
     }

     return clonedObj;
   }

   const clonedObject = deepClone(originalObject);
   

ThedeepClone() function uses recursion to clone each property of the object. It checks if the property is an object itself and recursively callsdeepClone() to clone nested objects. If the property is not an object, it is directly assigned to the cloned object. 3. UsingJSON.parse() andJSON.stringify():

1
2
3

   const clonedObject = JSON.parse(JSON.stringify(originalObject));
   

TheJSON.stringify() method converts the original object to a JSON string, andJSON.parse() then converts the string back to an object. This process creates a deep clone of the original object since the JSON representation does not retain any reference to the original object. Now you have a deep clone of the original object stored in theclonedObject variable. By following these steps, you can deep-clone an object in JavaScript using either recursion or theJSON.parse() andJSON.stringify() methods. Adjust the code as needed to fit your specific object structure and handle any additional requirements or edge cases.