Created
April 27, 2021 17:20
-
-
Save uttarwarsandesh33/9586e0c78f15a872b7730dcef8809f8c to your computer and use it in GitHub Desktop.
Deep copy with JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const originalObject = { | |
string: 'primitive string', | |
stringObj: new String('string obj'), | |
number: 100, | |
numberObj: new Number(100), | |
bigInt: BigInt("9007199254740991"), | |
nan: NaN, | |
array: [1, 2, 3], | |
arrayObj: new Array(2), | |
bool: false, | |
boolobj: new Boolean(false), | |
nul: null, | |
date: new Date(), | |
undef: undefined, | |
inf: Infinity, | |
regExp: /(\w+)\s(\w+)/ | |
} | |
const result = JSON.parse(JSON.stringify(originalObject)); | |
console.log(result); | |
{ | |
string: 'primitive string', | |
stringObj: 'string obj', // converted to primitive | |
number: 100, | |
numberObj: 100, // converted to primitive | |
bigInt: BigInt("9007199254740991"),// not JSON safe and throw error | |
nan: null, // forced to 'null' | |
array: [1, 2, 3], | |
arrayObj: [null, null], | |
bool: false, | |
boolobj: new Boolean(false), // converted to primitive | |
nul: null, | |
date: "2021-04-27T17:05:30.332Z", // stringified | |
undef: null, // forced to 'null' | |
inf: null, // forced to 'null' | |
regExp: null // forced to 'null' | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment