Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 290
Ram Avatar asked Jan 25 '17 09:01

Ram


People also ask

What is the difference between JSON parse and JSON Stringify?

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.

What is the most efficient way to deep clone an object in JavaScript?

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.

Does JSON parse JSON Stringify deep 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.


1 Answers

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 
like image 120
Ilja Everilä Avatar answered Oct 15 '22 07:10

Ilja Everilä