We can create a copy of object using Object.assign() and everything seem to be working fine, but here are some pitfalls lets check below example.
Properties on the prototype chain and non-enumerable properties cannot be copied.
This fixes the issue we had earlier. Now
Happy Coding!
let obj = { a: 1, b: { c: 2, }, } let newObj = Object.assign({}, obj); console.log(newObj); // { a: 1, b: { c: 2} } obj.a = 10; console.log(obj); // { a: 10, b: { c: 2} } console.log(newObj); // { a: 1, b: { c: 2} } newObj.a = 20; console.log(obj); // { a: 10, b: { c: 2} } console.log(newObj); // { a: 20, b: { c: 2} } newObj.b.c = 30; console.log(obj); // { a: 10, b: { c: 30} } console.log(newObj); // { a: 20, b: { c: 30} }
Why is obj.b.c = 30?
Properties on the prototype chain and non-enumerable properties cannot be copied.
How to fix?
This fixes the issue we had earlier. Now
newObj.b
has a copy and not a reference! This is a way to deep copy objects1 2 3 4 5 6 7 8 9 10 | let obj = { a: 1, b: { c: 2, }, } let newObj = JSON.parse(JSON.stringify(obj)); obj.b.c = 20; console.log(obj); // { a: 1, b: { c: 20 } } console.log(newObj); // { a: 1, b: { c: 2 } } (New Object Intact!) |
Happy Coding!