const target = {
field1: 1,
field2: undefined,
field3: 'ConardLi',
field4: {
child: 'child',
child2: {
child2: 'child2'
}
},
field5: null,
field6: [1, 2, 3, 4],
};
target.field7 = target;
const isObject = (val) => (typeof val === 'object' || typeof val === 'function') && val !== null
const deepClone = (target, map = new Map()) => {
if (isObject(target)) {
let targetCloned = Array.isArray(target) ? [] : {};
if (map.get(target)) {
return map.get(target);
}
map.set(target, targetCloned);
for (key in target) {
targetCloned[key] = deepClone(target[key], map);
}
return targetCloned;
} else {
return target;
}
return targetCloned;
}
const newVal = deepClone(target);
newVal.field1 = 2;
newVal.field6.push(5);
console.log(newVal)
console.log('111')
console.log(target)
console