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:
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: