Categories
Node.js Quick Tips Quick Tips

Deep clone values with structuredClone()

< 1 min read

This blog post is part of What’s new in Node.js core? March 2022 edition.

If you want to deep clone a value in Node.js, you no longer need to use a library or the JSON.parse(JSON.stringify(value)) hack. You can use the new global function structuredClone().

Contributed by Ethan Arrowood

Example of an object being deep cloned

const user = {
  name: "Lachlan Morris",
  address: { street: "Original Road", city: "Placeshire" },
};

const clonedUser = structuredClone(user);

clonedUser.address.street = "New Road";

console.log("user.address.street:", user.address.street);
// > Original Road

console.log("clonedUser.address.street:", clonedUser.address.street);
// > New Road

Support in Node.js

Also available in Deno, as well as Firefox, Chrome, Edge and Safari web browsers.

When can you use it in production?

structuredClone() might be backported to v16 (Active LTS) as a module (source: PR 40756).

It will be in v18 — initial release 19 Apr 2022, Active LTS starts 25 Oct 2022.

If you’d like to learn more about it, there’s a great write up on Axel Rauschmayer‘s blog.

Leave a Reply

Your email address will not be published. Required fields are marked *