实现函数
applyIf(obj1, obj2) {
if (typeof obj2 === 'object') {
Object.keys(obj2).forEach((key) => {
if (obj1[key]
&& ((typeof obj2[key] === 'object' && typeof obj1[key] === 'object')
|| (Array.isArray(obj1) && Array.isArray(obj2)))) {
this.applyIf(obj1[key], obj2[key]);
} else {
obj1[key] = obj2[key];
}
});
} else if (Array.isArray(obj1) && Array.isArray(obj2)) {
for (let i = 0; i < obj2.length; i += 1) {
if (i < obj1.length) {
if ((typeof obj2[i] === 'object' && typeof obj1[i] === 'object')
|| (Array.isArray(obj1) && Array.isArray(obj2))) {
this.applyIf(obj1[i], obj2[i]);
} else {
obj1[i] = obj2[i];
}
} else {
obj1.push(obj2[i]);
}
}
}
测试代码
const obj1 = { id: 1, name: 'zhangsan', sea: [{ a: '23', b: 'fffff', c: { d: 'kkkk', j: 'lllll' } }, 2, 3] };
const obj2 = { sea: [{ a: '11', c: { d: 'aaa', f: 'fff' } }, 5], name: 'lisi' };
this.applyIf(obj1, obj2);
console.log(obj1);