/ Gists / StructuredClone + set of all datatypes (@fatfish)
On gists

StructuredClone + set of all datatypes (@fatfish)

JavaScript

copy.js Raw #

// 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
}
*/