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)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…