Categories
JavaScript Answers

How to do deep copy in ES6 using the spread syntax?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *