Categories
JavaScript Answers

How to clone an object in JavaScript?

Spread the love

To clone an object in JavaScript, we can use JSON methods.

For instance, we write

const newObj = JSON.parse(JSON.stringify(oldObj));

to call JSON.stringify to convert oldObj into a JSON string.

And then we call JSON.parse to parse the JSON string back to an object.

Dates will be converted to strings with stringify so the parsed object will have date strings instead of date objects for dates.

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 *