JSON.parse(JSON.stringify(object)) efficiently creates a copy of simple objects by converting them to a JSON string and back, but loses complex data types like NaN, Set and Map. structuredClone preserves complex data types and handles NaN and Set, but doesn't support functions or symbols and may not be universally available.
original object containing various data such as undefined, Infinity, NaN, Date, RegExp, ArrayBuffer, Set and Map. Properties func and symbol are commented.
Preserves most data types including undefined, Infinity, NaN, RegExp, Date, Set, Map, ArrayBuffer.
Does not clone functions or symbols.
Suitable for complex objects and structures requiring accurate deep copying.
Case #1
console.log(clonedJSON.nan);// null// `clonedJSON.nan` will be `null` because `NaN` cannot be represented in JSON and is lost during the stringify operationconsole.log(clonedStructured.nan);// NaN// `clonedStructured.nan` remains `NaN` because `structuredClone` is designed to handle complex JavaScript objects and can correctly preserve `NaN` during the cloning process.
Case #2
console.log(clonedJSON.nested.set);// {}// `clonedJSON.nested.set` will be `{}` because the `Set` is lost during the `stringify` operation.console.log(clonedStructured.nested.set);// Set (3) {1, 2, 3}// `clonedStructured.nested.set` remains a `Set` object containing the same values `[1, 2, 3]` as in the `original` object.
Not really. Using the built in
structuredCloneis even easier, and works better:@jonrandy
Thanks 😊
Thanks you. Wasn't aware about this fn.
JSON.parse(JSON.stringify(object))efficiently creates a copy of simple objects by converting them to aJSONstring and back, but loses complex data types likeNaN,SetandMap.structuredClonepreserves complex data types and handlesNaNandSet, but doesn't supportfunctionsorsymbolsand may not be universally available.Let's take an example:
originalobject containing various data such asundefined,Infinity,NaN,Date,RegExp,ArrayBuffer,SetandMap. Propertiesfuncandsymbolare commented.JSON.parse(JSON.stringify(object))structuredCloneCase #1
Case #2
@jahid6597
Thanks 😊 As I am still learning and was not aware about the structuredClone