Skip to content

Instantly share code, notes, and snippets.

@Kcko
Created May 27, 2024 07:19
Show Gist options
  • Save Kcko/6c3e5789a1be7a8a4e415cfa42a7737f to your computer and use it in GitHub Desktop.
Save Kcko/6c3e5789a1be7a8a4e415cfa42a7737f to your computer and use it in GitHub Desktop.
// https://javascript.plainenglish.io/structuredclone-the-easiest-way-to-deep-clone-objects-in-javascript-c503b536266b
const testData = {
number: 123,
string: "test",
undefined: undefined,
null: null,
boolean: true,
object: { a: 1, b: { c: 2 } },
array: [1, 2, { d: 3 }],
// function: function() { return "hello"; },
map: new Map([["key1", "value1"], ["key2", "value2"]]),
set: new Set([1, 2, 3]),
date: new Date(),
error: new Error("An error occurred"),
regex: /test/i,
// domNode: document.createElement("div")
}
const structuredCloneResult = structuredClone(testData)
console.log(structuredCloneResult)
/*
{
number: 123,
string: "test",
undefined: undefined,
null: null,
boolean: true,
object: { a: 1, b: { c: 2 } },
array: [1, 2, { d: 3 }],
function: undefined, // Functions are not cloned
map: Map { 'key1' => 'value1', 'key2' => 'value2' },
set: Set { 1, 2, 3 },
date: 2023-05-23T09:00:00.000Z,
error: Error: An error occurred,
regex: /test/i,
domNode: undefined // DOM nodes are not cloned
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment