0
0
JavascriptHow-ToBeginner · 4 min read

How to Copy Object in JavaScript: Simple Methods Explained

To copy an object in JavaScript, you can use Object.assign({}, obj) or the spread syntax {...obj} for a shallow copy. For deep copying, use JSON.parse(JSON.stringify(obj)), but be aware it only works with JSON-safe data.
📐

Syntax

Here are common ways to copy an object in JavaScript:

  • Object.assign({}, obj): Copies all properties from obj into a new empty object.
  • {...obj}: Uses spread syntax to create a new object with the same properties.
  • JSON.parse(JSON.stringify(obj)): Converts the object to a JSON string and back to create a deep copy.
javascript
const original = { a: 1, b: 2 };

// Using Object.assign
const copy1 = Object.assign({}, original);

// Using spread syntax
const copy2 = { ...original };

// Using JSON methods for deep copy
const copy3 = JSON.parse(JSON.stringify(original));
💻

Example

This example shows how to copy an object and modify the copy without changing the original.

javascript
const person = { name: 'Alice', age: 25 };

// Shallow copy using spread
const copyPerson = { ...person };

copyPerson.age = 30;

console.log('Original:', person);
console.log('Copy:', copyPerson);
Output
Original: { name: 'Alice', age: 25 } Copy: { name: 'Alice', age: 30 }
⚠️

Common Pitfalls

Shallow copies only duplicate the top-level properties. Nested objects remain linked to the original. Using JSON.parse(JSON.stringify()) fails if the object has functions, undefined, or special types like Date.

Example of shallow copy issue:

javascript
const original = { name: 'Bob', details: { age: 40 } };

const shallowCopy = { ...original };
shallowCopy.details.age = 50;

console.log('Original details age:', original.details.age); // 50, changed unexpectedly

// Correct deep copy using JSON methods
const deepCopy = JSON.parse(JSON.stringify(original));
deepCopy.details.age = 60;
console.log('Original details age after deep copy change:', original.details.age); // 50, unchanged
Output
Original details age: 50 Original details age after deep copy change: 50
📊

Quick Reference

MethodDescriptionCopy TypeLimitations
Object.assign({}, obj)Copies properties to new objectShallowNested objects still linked
{ ...obj }Spread syntax to copy propertiesShallowNested objects still linked
JSON.parse(JSON.stringify(obj))Deep copy via JSON conversionDeepFails with functions, undefined, Dates

Key Takeaways

Use spread syntax or Object.assign for quick shallow copies of objects.
Shallow copies do not duplicate nested objects; changes affect the original.
Use JSON methods for deep copying simple objects without functions or special types.
Be careful with deep copy limitations like losing functions and special object types.
Always test your copy method to ensure it fits your object's structure.