brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: structuredClone makes a real deep copy of an object

Web-Development
~/tips/js-structuredclone

const copy = structuredClone(original);

Makes a full deep copy of a JavaScript object, including dates, maps and sets.

Copying an object with the spread operator only copies the top level. The nested objects are still shared, which is how bugs get in.

const copy = structuredClone(original);
copy.settings.theme = 'dark'; // original stays untouched

It is built into modern browsers and into Node.js 17 and newer. It also handles things that the old JSON.parse(JSON.stringify(x)) trick ruins, such as dates, maps, sets and nested arrays. A Date stays a Date and is not turned into a string.

Caveat: functions cannot be cloned. If the object contains one, structuredClone throws a DataCloneError. Class instances come out as plain objects without their methods.

Further reading: MDN: structuredClone

More Web-Development tips ab -n 200 -c 10 https://example.com/ console.assert(items.length > 0, 'cart is empty', items) document.designMode = "on" function save(item) { Save draft All Web-Development tips (67) All topics

Link