First, a deep copy of the object several methods
1. Using deep copy implemented recursively
1 function deepClone(obj){ 2 let objClone = Array.isArray(obj) ? [] : {}; 3 if (obj && typeof obj === 'object') { 4 for(let key in obj){ 5 if (obj[key] && typeof obj[key] === 'object'){ 6 objClone[key] = deepClone(obj[key]); 7 }else{ 8 objClone[key] = obj[key] 9 } 10 } 11 } 12 return objClone; 13 }
2. To achieve deep copy the object by JSON
function deepClone2(obj) { let _obj = JSON.stringify(obj), return JSON.parse(_obj); }
Note: The object methods can not achieve deep copy
3. By Object.assign () Copy
Note: When the object to be in a deep copy attribute;
When multiple stages of object attributes, the two properties is shallow copy
Second, a deep copy of the array several methods