Reputation: 61
var origin = { a: 1, b: { c: 2, d: 3 } }; // origin object
var copy_obj = { ...origin } // or Object.assign({}, origin.b)
delete copy_obj.b.c; // delete copy object
console.log(origin) // { a: 1, b: { d: 3 } };
I'm studying the invariant nature of things.
However, the above example shows that you want to delete the b.c. element of copy_obj. But the origin is also deleted.
Why is this happening?
Upvotes: 6
Views: 64
Reputation: 1122
Object.assign({}, origin.b)
or spread syntax {...obj}
performs a shallow copy. So the object stored in property b
of origin is not cloned i.e it maintains a reference to the object being nested.
Use the following to make a deep clone.
JSON.parse(JSON.stringify(obj))
var origin = { a: 1, b: { c: 2, d: 3 } }; // origin object
var copy_obj = JSON.parse(JSON.stringify(origin));
delete copy_obj.b.c;
console.log(origin)
Note: This only works for objects that can be serialized
For example:
// Object having functions
const obj= {
a: 1,
b: () => {return 2}
}
const copy = JSON.parse(JSON.stringify(obj));
// property `b` won't be copied as it is a function and can't be serialized.
console.log(copy)
Upvotes: 8