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)