Middle
What are the ways to copy an object in JavaScript?
sobes.tech AI
Answer from AI
In JavaScript, there are several ways to copy objects:
-
Shallow copy:
Object.assign({}, obj)— copies only the top level of properties.- Spread operator:
{ ...obj }— also a shallow copy.
-
Deep copy:
JSON.parse(JSON.stringify(obj))— a simple method, but does not copy functions, dates, undefined, etc.- Recursive function for deep copying.
- Using specialized libraries, e.g.,
lodash.cloneDeep.
Example of shallow copy:
const original = { a: 1, b: { c: 2 } };
const copy = { ...original };
copy.b.c = 3;
console.log(original.b.c); // 3 — changed because it is a shallow copy
Example of deep copy with JSON:
const original = { a: 1, b: { c: 2 } };
const deepCopy = JSON.parse(JSON.stringify(original));
deepCopy.b.c = 3;
console.log(original.b.c); // 2 — original remains unchanged