Sometimes, we want to do deep copy in ES6 using the spread syntax.
In this article, we’ll look at how to do deep copy in ES6 using the spread syntax.
How to do deep copy in ES6 using the spread syntax?
To do deep copy in ES6 using the spread syntax, we use JSON.stringify
and JSON.parse
.
For instance, we write
const oldObject = {
name: "A",
address: {
street: "Station Road",
city: "Pune",
},
};
const newObject = JSON.parse(JSON.stringify(oldObject));
to call JSON.stringify
with oldObject
to return the JSON string version of oldObject
.
Then we call JSON.parse
to parse the JSON string back to an object to return a deep clone of oldObject
.
Conclusion
To do deep copy in ES6 using the spread syntax, we use JSON.stringify
and JSON.parse
.