I want to know is there a difference between
Object.assign({}, obj)
and
JSON.parse(JSON.stringify(obj))
for deep cloning of an object? Can anyone explain if they have any idea?
The JSON. parse() function is used to convert a string into a JavaScript object while the JSON. stringify() function is used to convert a JavaScript object into a string.
According to the benchmark test, the fastest way to deep clone an object in javascript is to use lodash deep clone function since Object. assign supports only shallow copy.
Simple way of deep copying objects So, if you simply want to deep copy the object to another object, all you will need to do is JSON. stringify the object and parse it using JSON. parse afterward.
The difference is that
Object.assign({}, obj)
creates a shallow copy, not deep, while
JSON.parse(JSON.stringify(obj))
serializes the object as a JSON string and then deserializes it, effectively creating a deep copy. It should be noted that this method can only "deep copy" plain old data, not complex objects and their prototype.
A shallow copy is just fine, if all of your properties point to primitive values, or if you have no intention to mutate objects referenced by the copy. If you do, the changes will be visible in both the original and the shallow copy, because they both reference the same object:
> let a = { k: { h: 1 } }; > let b = Object.assign({}, a); > b.k.h = 2; > a { k: { h: 2 } } > b { k: { h: 2 } }
You of course can mutate the copy itself without it having any effect on the original:
> b.j = 4 > b.k = { new: 'object' } > a { k: { h: 2 } } > b { k: { new: 'object' }, j: 4 }
The serialize-deserialize trick on the other hand creates a deep copy where everything is created from scratch:
> let c = JSON.parse(JSON.stringify(b)); > c { k: { h: 2 } } > c.k.h = 3 > c { k: { h: 3 } } > a { k: { h: 2 } } > b { k: { h: 2 } }
Another way to inspect the identities is using strict equality:
> let a = { k: { h: 1 } }; > let b = Object.assign({}, a); > a.k === b.k // both point to the same object true > let c = JSON.parse(JSON.stringify(b)); > c.k === b.k // different objects false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With