How to deep copying an object with `JSON.parse` and `JSON.stringify`?
let me = {
firstName: 'Mischa',
lastName: 'Sega',
occupation: 'UX Engineer',
skills: [
{ name: 'JS' },
{ name: 'CSS' },
{
name: 'HTML',
misc: {
level: '9000 +'
}
}
]
}
let clone = JSON.parse(JSON.stringify(person))
// output: tl;dr exact copy of the `me` object
console.log(clone)
April 12th, 2020
The combination of JSON.parse()
with JSON.stringify()
is coming handy if you want to copy a deep nested object which has no function properties.
JSON.stringify()
converts the Javascript object to a JSON string. It expects one parameter. This is the value that has to be converted to a JSON string.
JSON.parse()
converts a JSON string to a Javascript object. It expects one parameter. This is the text that has to be converted to a Javascript object.