Open wangyuan0108 opened 4 years ago
var parent = { age: 20, hobby: [1, 2, 3], home: {city: '杭州'}, }; var child = extendDeep(parent); child.age = 26; child.hobby.push('4'); child.home.city = '上海'; console.log('child ', child); //[1, 2, 3, 4] console.log('parent ', parent); function extend(parent) { let child; if (Object.prototype.toString.call(parent) == '[object Object]') { child = {}; for (let key in parent) { child[key] = extend(parent[key]) } } else if (Object.prototype.toString.call(parent) == '[object Array]') { child = parent.map(item => extend(item)); } else { return parent; } return child; } function extendDeep(parent, child) { child = child || {}; for (var key in parent) { if (typeof parent[key] === "object") { child[key] = (Object.prototype.toString.call(parent[key]) === "[object Array]") ? [] : {}; extendDeep(parent[key], child[key]); } else { child[key] = parent[key]; } } return child; }
const newObj = JSON.parse(JSON.stringify(oldObj))