What is the difference between Object.assign and JSON.parse (JSON.stringify (obj)) for deep cloning an object?

I want to know if there is 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 ideas?

+7
javascript javascript-objects
source share
2 answers

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 
+13
source share

I think the result is the same, but the test performance difference, object.assign is much faster than JSON.parse (JSON.stringify (obj)).

So, if you care about performance, it is better to use object.assign

check the link below:

enter the link here

0
source share

All Articles