Is the below method a foolproof way of deep copying an object in Javascript i.e. even for very deeply nested objects/arrays ?
let newObj = JSON.parse(JSON.stringify(obj));
Is the below method a foolproof way of deep copying an object in Javascript i.e. even for very deeply nested objects/arrays ?
let newObj = JSON.parse(JSON.stringify(obj));
In short, this is a simple but unreliable deep copy that works for simple JavaScript objects. But it would likely fail for some non-primitive data types' properties.
const set = new Set();
set.add(1);
set.add(2);
const map = new Map();
map.set('Jessie', {phone: "213-555-1234", address: "123 N 1st Ave"})
const obj = {
foo: () => 'bar',
date: new Date(),
undefined,
set,
map,
}
console.log(obj);
let unreliableNewObj = JSON.parse(JSON.stringify(obj));
console.log(unreliableNewObj); // some properties are lost, some properties are changed like set and map, can compare the result
// ES6 shallow copy that may help
let reliableNewObj = {
...obj,
}
console.log(reliableNewObj);
// 'real' deep copy from library
// https://lodash.com/docs#cloneDeep
let deepObj = _.cloneDeep(obj); // if _ is imported
console.log(deepObj)
For a reliable deep copy, alternatives are: