How to copy an object
Short answer
The ... operator creates a new object with the same properties:
const user = { name: 'Anna', age: 25 };
const copy = { ...user };
copy.age = 26;
console.log(user.age, copy.age);Output:
25 26Nested objects
Such a copy is shallow: nested objects stay shared.
const user = { name: 'Anna', address: { city: 'London' } };
const copy = { ...user };
copy.address.city = 'Paris';
console.log(user.address.city);Output:
ParisA deep copy
structuredClone() copies the whole object, including all nested data:
const user = { name: 'Anna', address: { city: 'London' } };
const copy = structuredClone(user);
copy.address.city = 'Paris';
console.log(user.address.city);Output:
LondonCommon mistake
Assigning an object to another variable does not copy it: both variables point to the same object:
const user = { name: 'Anna' };
const copy = user;
copy.name = 'Oleg';
console.log(user.name);Output:
OlegFunctions used in this recipe
- structuredClone — Creates a deep copy of an object with all nested data.
- Object.assign — Copies properties from some objects into another.
- JSON.stringify — Converts a value to a JSON string.