How to Deep Clone an Object in JavaScript?

Estimated read time 1 min read

One way to deep clone an object in JavaScript is to use the JSON.parse(JSON.stringify(obj)) method. This method serializes the object to a JSON string, then parses the string back into a new object. This works for objects with properties that can be represented as JSON data.

Here’s an example:

const original = { a: 1, b: { c: 2 } };
const clone = JSON.parse(JSON.stringify(original));

Another way to deep clone an object is to use a combination of Object.assign() and the spread operator ... to create a new object with the properties and values of the original object.

Here’s an example:

const original = { a: 1, b: { c: 2 } };
const clone = Object.assign({}, original);
const deepClone = JSON.parse(JSON.stringify(original), (key, value) =>
  typeof value === "object" ? Object.assign({}, value) : value
);

This approach recursively creates a new object for each nested object in the original.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply