The difference is that
Object.assign({}, obj)
creates a shallow copy , not deep , but
JSON.parse(JSON.stringify(obj))
serializes the object as a JSON string and then deserializes it, effectively creating a deep copy.
A shallow copy is perfect if all of your properties point to primitive values, or if you do not intend to mutate the objects referenced by the copy. If you do this, the changes will be visible both in the original and in the shallow copy, since both of them refer to the same object:
> let a = { k: { h: 1 } }; > let b = Object.assign({}, a); > bkh = 2; > a { k: { h: 2 } } > b { k: { h: 2 } }
Of course, you can mutate the instance itself without affecting the original:
> bj = 4 > bk = { new: 'object' } > a { k: { h: 2 } } > b { k: { new: 'object' }, j: 4 }
On the other hand, a serialized deserialization trick creates a deep copy where everything is created from scratch:
> let c = JSON.parse(JSON.stringify(b)); > c { k: { h: 2 } } > ckh = 3 > c { k: { h: 3 } } > a { k: { h: 2 } } > b { k: { h: 2 } }
Another way to verify identifiers is to strictly equality:
> let a = { k: { h: 1 } }; > let b = Object.assign({}, a); > ak === bk // both point to the same object true > let c = JSON.parse(JSON.stringify(b)); > ck === bk // different objects false
Ilja everilΓ€
source share