Skip to main content

Deep Copy of an Object

You are required to implement a deep copy of an object.

A deep copy is a process in which the entire object is copied to a new object, including all nested objects and their properties.

Example of usage

const obj = {
a: 1,
b: {
c: 2,
d: 3,
},
};

const clonedObj = deepClone(obj);

console.log(clonedObj); // { a: 1, b: { c: 2, d: 3 } }

Pass by value vs. Pass by Reference

As was described in this article Pass by value and reference when we dealing with primitive data types

Shallow vs Deep Clone

There are two main types of cloning: shallow cloning and deep cloning.

It's important to understand the difference, especially when dealing with nested structures.

  • Shallow copy only duplicates the first level of properties or elements of an object or array. This means changes to the nested objects in the clone will affect the original object as well.
  • Deep copy creates a new object with the same properties as the original, and recursively clones all nested objects and arrays. This ensures that the clone is completely independent of the original object, and changes to one will not affect the other.

Shallow Copy

Using spread operator

const obj = { a: 1, b: 2 };
const clone = { ...obj };
console.log(clone); // { a: 1, b: 2 }

Using Object.assign

const obj = { a: 1, b: 2 };
const clone = Object.assign({}, obj);
console.log(clone); // { a: 1, b: 2 }

Deep Clone

Deep cloning with structuredClone()

The structuredClone method is a modern and efficient way to deep clone objects, available in modern browsers.

const obj = { 
a: 1,
b: {
c: 2,
}
};

const clone = structuredClone(obj);
console.log(clone); // { a: 1, b: { c: 2 } }

Deep cloning with recursion

To implement a deep clone of an object in JavaScript, you can use recursion to ensure that all nested objects and their properties are also copied.

Algorithm

  1. The deepClone function takes an object as an argument and returns a deep clone of the object.
  2. If the object is null or not an object, it returns the object as is.
  3. Create a new object clonedObj based on the type of the input object (array or object).
  4. Iterate over the keys of the input object and recursively calls deepClone on each value to create a deep clone of the nested objects.
  5. Return the cloned object at the end.

Code


function deepClone(obj) {
// check if the value is an object
if (obj === null || typeof obj !== 'object') {
return obj;
}

// create an array or object to hold the values
const clonedObj = Array.isArray(obj) ? [] : {};

// recursively copy each property
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
clonedObj[key] = deepClone(obj[key]);
}
}

return clonedObj;
}

Summary

  • There are two ways to clone an object: shallow and deep
  • Shallow copy duplicates only top-level properties
  • Deep copy recursively clones all properties, ensuring full independence from the original object.

References