DEV Community

Cover image for Deep Cloning Objects in JavaScript, the Modern Way
Steve Sewell for Builder.io

Posted on Edited on Originally published at builder.io

Deep Cloning Objects in JavaScript, the Modern Way

Did you know, there's now a native way in JavaScript to do deep copies of objects?

That's right, this structuredClone function is built into the JavaScript runtime:



const calendarEvent = {
  title: "Builder.io Conf",
  date: new Date(123),
  attendees: ["Steve"]
}

// 😍
const copied = structuredClone(calendarEvent)


πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung

Did you notice in the example above we not only copied the object, but also the nested array, and even the Date object?

And all works precisely as expected:



copied.attendees // ["Steve"]
copied.date // Date: Wed Dec 31 1969 16:00:00
cocalendarEvent.attendees === copied.attendees // false


πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung

That’s right, structuredClone can not only do the above, but additionally:

  • Clone infinitely nested objects and arrays
  • Clone circular references
  • 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

So for example, this madness would even work as expected:



const kitchenSink = {
  set: new Set([1, 3, 3]),
  map: new Map([[1, 2]]),
  regex: /foo/,
  deep: { array: [ new File(someBlobData, 'file.txt') ] },
  error: new Error('Hello!')
}
kitchenSink.circular = kitchenSink

// βœ… All good, fully and deeply copied!
const clonedSink = structuredClone(kitchenSink)


πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung

Why not just object spread?

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:



const simpleEvent = {
  title: "Builder.io Conf",
}
// βœ… no problem, there are no nested objects or arrays
const shallowCopy = {...calendarEvent}


πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung

Or even one of these, if you prefer



const shallowCopy = Object.assign({}, simpleEvent)
const shallowCopy = Object.create(simpleEvent)


πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung

But as soon as we have nested items, we run into trouble:



const calendarEvent = {
  title: "Builder.io Conf",
  date: new Date(123),
  attendees: ["Steve"]
}

const shallowCopy = {...calendarEvent}

// 🚩 oops - we just added "Bob" to both the copy *and* the original event
shallowCopy.attendees.push("Bob")

// 🚩 oops - we just updated the date for the copy *and* original event
shallowCopy.date.setTime(456)


πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung

As you can see, we did not make a full copy of this object.

The nested date and array are still a shared reference between both, which can cause us major issues if we want to edit those thinking we are only updating the copied calendar event object.

Why not JSON.parse(JSON.stringify(x)) ?

Ah yes, this trick. It is actually a great one, and is surprisingly performant, but has some shortcomings that structuredClone addresses.

Take this as an example:



const calendarEvent = {
  title: "Builder.io Conf",
  date: new Date(123),
  attendees: ["Steve"]
}

// 🚩 JSON.stringify converted the `date` to a string
const problematicCopy = JSON.parse(JSON.stringify(calendarEvent))


πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung

If we log problematicCopy, we would get:



{
  title: "Builder.io Conf",
  date: "1970-01-01T00:00:00.123Z"
  attendees: ["Steve"]
}


πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung

That’s not what we wanted! date is supposed to be a Date object, not a string.

This happened because JSON.stringify can only handle basic objects, arrays, and primitives. Any other type can be handled in hard to predict ways. For instance, Dates are converted to a string. But a Set is simply converted to {}.

JSON.stringify even completely ignores certain things, like undefined or functions.

For instance, if we copied our kitchenSink example with this method:



const kitchenSink = {
  set: new Set([1, 3, 3]),
  map: new Map([[1, 2]]),
  regex: /foo/,
  deep: { array: [ new File(someBlobData, 'file.txt') ] },
  error: new Error('Hello!')
}

const veryProblematicCopy = JSON.parse(JSON.stringify(kitchenSink))


πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung

We would get:



{
  "set": {},
  "map": {},
  "regex": {},
  "deep": {
    "array": [
      {}
    ]
  },
  "error": {},
}


πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung

Ew!

Oh yeah, and we had to remove the circular reference we originally had for this, as JSON.stringify simply throws errors if it encounters one of those.

So while this method can be great if our requirements fit what it can do, there is a lot that we can do with structuredClone (aka everything above that we failed to do here) that this method cannot.

Why not _.cloneDeep?

To date, Lodash’s cloneDeep function has been a very common solution to this problem.

And this does, in fact, work as expected:



import cloneDeep from 'lodash/cloneDeep'

const calendarEvent = {
  title: "Builder.io Conf",
  date: new Date(123),
  attendees: ["Steve"]
}

// βœ… All good!
const clonedEvent = structuredClone(calendarEvent)


πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung

But, there is just one caveat here. According to the Import Cost extension in my IDE, that prints the kb cost of anything I import, this one function comes in at a whole 17.4kb minified (5.3kb gzipped):

Screenshot of the import cost of 'lodash/cloneDeep' at 5.3kb gzipped

And that assumes you import just that function. If you instead import the more common way, not realizing that tree shaking doesn’t always work the way you hoped, you could accidentally import up to 25kb just for this one function 😱

Screenshot of the import cost of 'lodash' at 25kb

While that will not be the end of the world to anyone, it’s simply not necessary in our case, not when browsers already have structuredClone built in.

What can structuredClone not clone

Functions cannot be cloned

They will a throw aΒ DataCloneErrorΒ exception:



// 🚩 Error!
structuredClone({ fn: () => { } })

πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung




DOM nodes

Also throws a DataCloneErrorΒ exception:



// 🚩 Error!
structuredClone({ el: document.body })

πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung




Property descriptors, setters, getters

And similar metadata-like features are not cloned.

For instance, with a getter, the resulting value is cloned, but not the getter function itself (or any other property metadata):



structuredClone({ get foo() { return 'bar' } })
// Becomes: { foo: 'bar' }

πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung




Object prototypes

The prototype chain is not walked or duplicated. So if you clone an instance of MyClass, the cloned object will no longer be known to be an instance of this class (but all valid properties of this class will be cloned)



class MyClass {
foo = 'bar'
myMethod() { /* ... */ }
}
const myClass = new MyClass()

const cloned = structuredClone(myClass)
// Becomes: { foo: 'bar' }

cloned instanceof myClass // false

πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung




Full list of supported types

More simply put, anything not in the below list cannot be cloned:

  • JS Built-ins
    • Array, ArrayBuffer, Boolean, DataView, Date, ErrorΒ types (those specifically listed below), Map , Object but only plain objects (e.g. from object literals), Primitive types, exceptΒ symbol (aka number, string, null, undefined, boolean, BigInt), RegExp, Set, TypedArray
  • Error types
    • Error, EvalError, RangeError, ReferenceError , SyntaxError, TypeError, URIError
  • Web/API types
    • AudioData, Blob, CryptoKey, DOMException, DOMMatrix, DOMMatrixReadOnly, DOMPoint, DomQuad, DomRect, File, FileList, FileSystemDirectoryHandle, FileSystemFileHandle, FileSystemHandle, ImageBitmap, ImageData, RTCCertificate, VideoFrame

Browser and runtime support

And here is the best part - cloneDeep is supported in all major browsers, and even Node.js and Deno.

Just note the caveat with Web Workers having more limited support:

Screenshot of the browser support table linked to below

Source: MDN

Conclusion

It’s been a long time coming, but we finally now have structuredClone to make deep cloning objects in JavaScript a breeze. Thank you, Surma.

About me

Hi! I'mΒ Steve, CEO ofΒ Builder.io.

We make a way to drag + drop with your components to create pages and other CMS content on your site or app, visually.

You can read more about how this can improve your workflow here.

You may find it interesting or useful:

Builder.io demo gif

Top comments (15)

πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung
 
pengeszikra profile image
Peter Vivo •

Good to know!

The whole support for workers is narrower: mdn: structuredClone

Image description

πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung
 
kixxauth profile image
Kris Walker •

Sixteen years in JavaScript and I never knew this existed! Nice.

So, you mentioned that JSON.parse(JSON.stringify()) is surprisingly performant; and it is on most web browsers. But on single or dual core CPUs, which are common in embedded devices like smart TVs, set-top boxes, kiosks, and gaming consoles, the JSON parsing and stringification blocks the runtime enough that it can dramatically hit performance.

πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung
 
fruntend profile image
fruntend •

Π‘ongratulations πŸ₯³! Your article hit the top posts for the week - dev.to/fruntend/top-10-posts-for-f...
Keep it up πŸ‘

πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung
 
rahul_jindal profile image
Rahul Jindal •

Thanks for sharing this. I got to know something completely new and it seems very powerful also.

πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung
 
sahibjadatalib_ansari profile image
Sahibjadatalib Ansari • • Edited

super

πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung
 
mindplay profile image
Rasmus Schultz •

There's a polyfill at just 1K (min+gzip) so this is quite a bit smaller than underscore, just note the limitations listed in the README.

πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung
 
remrkabledev profile image
Malcolm R. Kente •

Awesome, alleviates a lot of effort into deep cloning.
Cheers for the post πŸš€πŸš€πŸš€

πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung
 
parthprajapati profile image
Parth •

Good effort, thank you so very much for this effort.

πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung
 
webduvet profile image
webduvet •

Perhaps you could have mentioned also where it does not work - if object contains function or on DOM elements. It also does not work on instances and does work differently on instances of native js objects. I've never used it that way and never looked it up, but here is some food for thoughts.

d1 = new Date();
d2 = structuredClone(d1);

d1.__proto__ === d2.__proto__
// true

function Test() {}
Test.prototype.fn = function() {}

t1 = new Test()
t2 = structuredClone(t1);

t1.__proto__ === t2.__proto__
// false
πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung
πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung
 
steve8708 profile image
Steve Sewell Builder.io •

Great feedback - just updated the article with a new section on this, thanks!

πŸ”₯ Jadwal & Hasil: builderio/deep cloning objects in javascript the modern way kf - Jadwal Siaran Langsung
 
ivofehn profile image
IvoFehn •

I already saw this before and wondered where the exact difference is. Really helpful post!

Some comments have been hidden by the post's author - find out more