logologo
  • Dashboard
  • Features
  • AI Tools
  • FAQs
  • Jobs
  • Modus
logologo

We source, screen & deliver pre-vetted developers—so you only interview high-signal candidates matched to your criteria.

Useful Links

  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation
  • About Us

Resources

  • Certifications
  • Topics
  • Collections
  • Articles
  • Services

AI Tools

  • AI Interviewer
  • Xperto AI
  • Pre-Vetted Top Developers

Procodebase © 2025. All rights reserved.

Q: Implement a deep clone of an object?

author
Generated by
ProCodebase AI

29/10/2024

JavaScript

When working with objects in JavaScript, it's important to understand the difference between deep cloning and shallow cloning. Shallow cloning creates a new object that copies over the references of the original object's properties, while deep cloning ensures that all nested properties are replicated, creating entirely new instances of those objects.

Shallow Clone vs. Deep Clone

To make this clearer, let’s look at an example:

const original = { name: "Alice", address: { city: "Wonderland", zip: 12345 } }; const shallowClone = Object.assign({}, original); shallowClone.address.city = "New Town"; console.log(original.address.city); // Outputs: "New Town"

In the code above, modifying shallowClone.address.city also changes original.address.city because both objects share the same reference for the nested address object. To prevent this, we need to perform a deep clone.

Methods to Deep Clone an Object

1. Using JSON Methods

The simplest way to deep clone an object is by using JSON.parse and JSON.stringify. However, this method comes with some limitations:

const deepCloneJSON = (obj) => { return JSON.parse(JSON.stringify(obj)); }; const clonedObject = deepCloneJSON(original); clonedObject.address.city = "New City"; console.log(original.address.city); // Outputs: "Wonderland"

Limitations:

  • This method cannot clone functions, dates, undefined, or symbols.
  • It doesn't maintain prototypes or handle circular references.

2. Using a Recursive Function

For more control, we can write a recursive function that copies properties manually:

const deepCloneRecursive = (obj) => { if (obj === null || typeof obj !== 'object') { return obj; // Return the value if obj is not an object } const clone = Array.isArray(obj) ? [] : {}; for (let key in obj) { if (obj.hasOwnProperty(key)) { clone[key] = deepCloneRecursive(obj[key]); // Recursively clone properties } } return clone; }; const clonedRecursiveObject = deepCloneRecursive(original); clonedRecursiveObject.address.city = "New City"; console.log(original.address.city); // Outputs: "Wonderland"

3. Using Lodash Library

If you're working on a project where you already have Lodash included, it has a built-in function for deep cloning:

const _ = require('lodash'); const clonedWithLodash = _.cloneDeep(original); clonedWithLodash.address.city = "New City"; console.log(original.address.city); // Outputs: "Wonderland"

Lodash’s cloneDeep method handles various data types and is optimized for performance.

4. Using Structured Clone (Browser Native)

In modern browsers, you can use the newer structuredClone function, which is efficient for cloning many types of objects.

const clonedStructured = structuredClone(original); clonedStructured.address.city = "New City"; console.log(original.address.city); // Outputs: "Wonderland"

Advantage:

  • This method can clone more complex data types like Map, Set, and even objects with circular references.

Conclusion

Understanding deep cloning is crucial when manipulating JavaScript objects, particularly when nested structures are involved. Choose the method that fits your needs, considering the data types and structures you are working with. Happy coding!

Popular Tags

JavaScriptdeep clonecloning objects

Share now!

Related Questions

  • How does prototypal inheritance work in JavaScript

    17/11/2024 | VanillaJS

  • How does call

    17/11/2024 | VanillaJS

  • How does JavaScript handle asynchronous code

    29/10/2024 | VanillaJS

  • Explain prototypal inheritance in JS

    29/10/2024 | VanillaJS

  • What are closures and how do they help with data privacy in JavaScript

    17/11/2024 | VanillaJS

  • apply

    17/11/2024 | VanillaJS

  • How does JavaScript handle asynchronous code execution

    17/11/2024 | VanillaJS

Popular Category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design