Deep cloning is the process of creating a copy of an object along with all nested properties ( Including other objects ), ensuring that we do not mutate original object ( Changes to the clone do not affect the original object ). Unlike shallow cloning, which only copies the top-level properties, deep cloning creates independent copies of all nested properties.

Snippets

Using Json Methods


const original = {
  name: 'Johnny B. Goode',
  age: 36,
  address: {
    city: 'New York',
    zip: '10001'
  }
};

const deepClone = JSON.parse(JSON.stringify(original));

// Modifying the clone
deepClone.address.city = 'Los Angeles';

// Original object remains unchanged
console.log(original.address.city); // Output: New York
console.log(deepClone.address.city); // Output: Los Angeles

One straightforward way to achieve deep cloning is using JSON methods, although this approach has limitations with functions, undefined properties, and special objects like Dates and RegExps. Need a robust solution ? Use the structuredClone function, or a library like Lodash ( Provide a reliable cloneDeep method ).

Using structuredClone


const original = {
  name: 'Johnny B. Goode',
  age: 36,
  address: {
    city: 'New York',
    zip: '10001'
  }
};

const deepClone = structuredClone(original);

// Modifying the clone
deepClone.address.city = 'Los Angeles';

// Original object remains unchanged
console.log(original.address.city); // Output: New York
console.log(deepClone.address.city); // Output: Los Angeles

Using Lodash cloneDeep


const _ = require('lodash');

const original = {
  name: 'Johnny B. Goode',
  age: 36,
  address: {
    city: 'New York',
    zip: '10001'
  }
};

const deepClone = _.cloneDeep(original);

// Modifying the clone
deepClone.address.city = 'Los Angeles';

// Original object remains unchanged
console.log(original.address.city); // Output: New York
console.log(deepClone.address.city); // Output: Los Angeles

While JSON methods provide a quick solution for simple objects, structuredClone and libraries like Lodash offer a more robust and versatile option to deep clone in JavaScript.

Article continues below

Our Sponsored Pick
| TrustScore 4.6

So I know our tutorials are totally awesome 😉. But maybe, going through how-to's is not how you would like to be spending your precious time. Imagine a world where things just work. Kinsta's hosting platform gets our official -"Easy Way of the Day" seal. Advanced features that are incredibly easy to set up.

Pros:
  • Cloudflare integration
  • Automatic daily backups
  • DDoS protection
Cons:
  • Exclusively for WordPress
Explore Platform Read Reviews
We earn a commission if you click this link and make a purchase at no additional cost to you.
09/11/2024 3:10 am UTC

Footnotes: