How to Deep Copy Object in JavaScript: Simple Guide
To deep copy an object in JavaScript, use
structuredClone(object) for a full independent copy including nested objects. Alternatively, use JSON.parse(JSON.stringify(object)) for simple objects without functions or special types.Syntax
The most modern way to deep copy an object is using structuredClone(object). This creates a complete copy including nested objects.
Another common method is JSON.parse(JSON.stringify(object)), which converts the object to a string and back to a new object.
javascript
const copy1 = structuredClone(originalObject); const copy2 = JSON.parse(JSON.stringify(originalObject));
Example
This example shows how to deep copy an object with nested properties using both methods and how changes to the copy do not affect the original.
javascript
const original = { name: "Alice", details: { age: 25, hobbies: ["reading", "hiking"] } }; // Using structuredClone (modern and recommended) const copyStructured = structuredClone(original); copyStructured.details.age = 30; // Using JSON methods const copyJSON = JSON.parse(JSON.stringify(original)); copyJSON.details.hobbies.push("coding"); console.log("Original:", original); console.log("Copy with structuredClone:", copyStructured); console.log("Copy with JSON methods:", copyJSON);
Output
Original: { name: 'Alice', details: { age: 25, hobbies: [ 'reading', 'hiking' ] } }
Copy with structuredClone: { name: 'Alice', details: { age: 30, hobbies: [ 'reading', 'hiking' ] } }
Copy with JSON methods: { name: 'Alice', details: { age: 25, hobbies: [ 'reading', 'hiking', 'coding' ] } }
Common Pitfalls
Using JSON.parse(JSON.stringify(object)) fails if the object contains functions, undefined, Date, Map, Set, or other special types because they get lost or converted incorrectly.
Example of failure:
javascript
const obj = { date: new Date(), func: () => "hello", value: undefined }; const copy = JSON.parse(JSON.stringify(obj)); console.log(copy); // { date: string } - func and undefined lost
Output
{ date: "2024-06-...T...Z" }
Quick Reference
- structuredClone(object): Best for full deep copy including special types (modern browsers and Node.js 17+).
- JSON.parse(JSON.stringify(object)): Simple but limited to JSON-safe data.
- Avoid shallow copy methods like
Object.assign()or spread operator for nested objects.
Key Takeaways
Use structuredClone(object) for a reliable deep copy including nested objects and special types.
JSON.parse(JSON.stringify(object)) works only for simple JSON-safe objects without functions or special types.
Shallow copy methods do not copy nested objects and can cause bugs.
Be aware that JSON methods lose functions, undefined, and special objects like Date or Map.
structuredClone is supported in modern environments; check compatibility if needed.