DEV Community


Posted on

Fantastic New way for deep copy of JavaScript Object

JavaScript has a good way to deep copy of JavaScript Object - structuredClone().

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

The method also allows transferable objects in the original value to be transferred rather than cloned to the new object. Transferred objects are detached from the original object and attached to the new object; they are no longer accessible in the original object.

structuredClone(value, transferables)
Enter fullscreen mode Exit fullscreen mode

This function can be used to deep copy JavaScript values. It also supports circular references, as shown below:

// Create an object with a value and a circular reference to itself.
const original = { name: "MDN" };
original.itself = original;

// Clone it
const clone = structuredClone(original);

console.assert(clone !== original); // the objects are not the same (not same identity)
console.assert( === "MDN"); // they do have the same values
console.assert(clone.itself === clone); // and the circular reference is preserved
Enter fullscreen mode Exit fullscreen mode


Transferable objects (only) can be transferred rather than duplicated in the cloned object, using the optional parameter's transfer value. Transferring makes the original object unusable.

The following code shows how to clone an array and transfer its underlying resources to the new object. On return, the original uInt8Array.buffer will be cleared.

var uInt8Array = new Uint8Array(1024 * 1024 * 16); // 16MB
for (var i = 0; i < uInt8Array.length; ++i) {
  uInt8Array[i] = i;

const transferred = structuredClone(uInt8Array, { transfer: [uInt8Array.buffer] });
console.log(uInt8Array.byteLength);  // 0
Enter fullscreen mode Exit fullscreen mode

You can clone any number of objects and transfer any subset of those objects. For example, the code below would transfer arrayBuffer1 from the passed in value, but not arrayBuffer2.

const transferred = structuredClone(
   { x: { y: { z: arrayBuffer1, w: arrayBuffer2 } } },
   { transfer: [arrayBuffer1] });
Enter fullscreen mode Exit fullscreen mode

Enjoy Hack!~!

Top comments (1)

raddevus profile image

Searched for "javascript deep copy" and this is the only entry I found that shows this structuredClone method. Great help and it works exactly the way I need it to in order to solve a problem. Thanks for the post.