Deep copy object in JS / ES6

olaj

Ola Johansson

Posted on December 29, 2022

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

💖 💪 🙅 🚩
olaj
Ola Johansson

Posted on December 29, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related