0
0
JavascriptHow-ToBeginner · 3 min read

How to Deep Clone Object Using JSON in JavaScript

You can deep clone an object in JavaScript by converting it to a JSON string with JSON.stringify() and then parsing it back to an object with JSON.parse(). This creates a new object with the same data but no shared references to the original.
📐

Syntax

The syntax to deep clone an object using JSON is simple:

  • JSON.stringify(object) converts the object into a JSON string.
  • JSON.parse(string) converts the JSON string back into a new object.

Combining these two creates a deep copy of the original object.

javascript
const deepClone = JSON.parse(JSON.stringify(originalObject));
💻

Example

This example shows how to deep clone an object and modify the clone without affecting the original.

javascript
const original = { name: "Alice", details: { age: 25, city: "Wonderland" } };
const clone = JSON.parse(JSON.stringify(original));
clone.details.age = 30;
console.log("Original age:", original.details.age);
console.log("Cloned age:", clone.details.age);
Output
Original age: 25 Cloned age: 30
⚠️

Common Pitfalls

Using JSON methods to deep clone has some limitations:

  • It does not copy functions, undefined, Symbol, or special object types like Date or RegExp.
  • It cannot handle circular references and will throw an error if the object contains them.
  • It converts Date objects to strings, losing their original type.

For complex objects, consider other cloning methods or libraries.

javascript
const obj = { date: new Date(), func: () => {}, undef: undefined };
const clone = JSON.parse(JSON.stringify(obj));
console.log(clone); // { date: "2024-06-...T...Z" } - functions and undefined are lost
Output
{"date":"2024-06-...T...Z"}
📊

Quick Reference

Summary tips for deep cloning with JSON:

  • Use JSON.stringify() and JSON.parse() for simple objects without functions or special types.
  • Avoid if your object has circular references or non-serializable values.
  • For complex cloning, use libraries like lodash.cloneDeep().

Key Takeaways

Use JSON.stringify and JSON.parse together to deep clone simple objects.
This method does not clone functions, undefined, or special objects like Date.
It fails on objects with circular references and throws an error.
For complex objects, use specialized cloning libraries like lodash.
Always test cloned objects to ensure data integrity after cloning.