Deep copy object in JS / ES6
Ola Johansson
Posted on December 29, 2022
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 }
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)
);
Reference: Stack Overflow
💖 💪 🙅 🚩
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
webdev Adding Interactive Charts and Graphs to Tailwind CSS Admin Templates: A Step-by-Step Guide
November 30, 2024
tailwindcss Integrating Tailwind CSS with Other Frontend Frameworks for Admin Panels
November 30, 2024
react How to add loading states with server action and useActionState hook in Nextjs 15 and React 19
November 30, 2024