Friday, August 26, 2016

Shallow copy and Deep copy javascript object using native or underscore.js

Unfortunately there is no method in javascript to clone a javascript object. So if you do something like

a = {key: 'value'}
b = a

Internally in javascript the reference of the object is store in variable copied to b so both variable pointing to the same object.

Underscore.js provide clone method which shallow copy the object. so if i do something like

a = {key: 'value'}
b = _.clone(a)

Both a and b variable have different references.

As underscore.js clone method does shallow copy, objects inside the variable a and b remains same. so if i do something like

a = {key: 'value', key2: {key3: 'value2'}}
b = _.clone(a)

Both variables have different references but the key2 still have the same reference. So if i do any activity on key2 it will affect both objects.

Now my requirement is to have a deep copy rather than shallow copy. To achieve this i use the power of JSON. so if i do something like

a = {key: 'value', key2: {key3: 'value2'}}
b = JSON.parse(JSON.stringify(a))

Now both variables having different references and object is deep copied.

No comments: