Copying Javascript objects can be tricky. Most of the time, we will do shallow copy of an object in javascript.
But, there are few problems associated with that approach. But getting into that topic, we will see what is shallow and deep copy in javsacript.
In javascript, shallow copy only clones the top level of an object. if an object contains the nested or reference object. it will copy only the reference to it.
For example, let’s say you have an object like this
let data = {
"id" : 1,
"name" : "john",
"address" : {
"street" : "Sample",
"country" : "Earth",
"Street" : "Madison street"
}
}
you are copying the object to a new variable using Object.assign
copydata = Object.assign({},data);
After that, if you console log the copydata variable. you will get the output like
Now, you are changing the variable data’s object
data.address.street = "Changed Street";
if you console log copydata again, you will get output like,
it changes the copied object value too because the copied object will refer to the same object.
To solve this problem, deep copying is used in javascript.
Meanwhile, deep copying in javascript clones the nested objects too and stores it in the different memory location.
So, changing the original object doesn’t affect the cloned object.
it can be achieved using lodash util library in javascript which is one of the popular library in javascript ecosystem.
Install lodash in your machine to use it. After that, there is a method called clonedeep in lodash which is used to achieve the deep copying in javascript.
Thanks for reading !
#javascript