Deep clone objects in JavaScript with structuredClone()
JavaScript Dasun Kalupahana 87 views
const orig = { user: { name: "Ada", tags: ["a"] }, when: new Date(0), ids: new Set([1, 2]) };
const copy = structuredClone(orig);
copy.user.tags.push("b");
console.log(orig.user.tags, copy.user.tags);
console.log(copy.when instanceof Date, copy.ids instanceof Set);
// [ 'a' ] [ 'a', 'b' ]
// true true
Makes a true deep copy and keeps Date, Set and Map. It avoids the JSON.parse(JSON.stringify()) hack, which turns Dates into strings and drops Sets. Needs Node 17+, Chrome 98, Firefox 94 or Safari 15.4.
Learn more on the blog
Javascript
structuredClone vs JSON.stringify vs Spread: Deep Copy Guide
Sooner or later every JavaScript developer copies an object, changes the copy,...
3 min read