DEV Community

Ola Johansson
Ola Johansson

Posted on

Deep copy object in JS / ES6

This is a thing I'm running into pretty often. In a test or whatnot i want clean data for each test. I usually just use the spread syntax.

const mockEvent = {...testData.events.defaultEventRegularSite }
Enter fullscreen mode Exit fullscreen mode

But the problem with this is that it actually just do a shallow copy. If you want to get a totally clean object this wont work if the object has more nested properties.

If you want a deep copy, you can use JSON like this.

const mockEvent = JSON.parse(
   JSON.stringify(testData.events.defaultEventRegularSite)
);
Enter fullscreen mode Exit fullscreen mode

Reference: Stack Overflow

Top comments (0)

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay