Dan Stroot

Deep Cloning Objects in JavaScript

The global structuredClone() method creates a deep clone of a given value using the structured clone algorithm.

Date:


Did you know, there's now a native way in JavaScript to do deep copies of objects? That's right, the structuredClone function is built into the JavaScript runtime:

deep.js
(javascript)
const calendarEvent = {
  title: 'Builder.io Conf',
  date: new Date(123),
  attendees: ['Steve'],
}
 
// 😍
const copied = structuredClone(calendarEvent)

In the example above we not only copied the object, but also the nested array, and even the Date object. And it all works precisely as expected, plus structuredClone can:

  • Clone infinitely nested objects and arrays
  • Clone circular references (really! but why?)
  • Clone a wide variety of JavaScript types, such as Date, Set, Map, Error, RegExp, ArrayBuffer, Blob, File, ImageData, and many more
  • Transfer any transferable objects

It is important to note we are talking about a deep copy. If you just need to do a shallow copy, aka a copy that does not copy nested objects or arrays, then we can just do an object spread:

shallow.js
(javascript)
const simpleEvent = {
  title: 'Builder.io Conf',
}
// ✅ no problem, there are no nested objects or arrays
const shallowCopy = { ...calendarEvent }

References

Sharing is Caring

Edit this page