// function deepAssign(...param) {
// let result = Object.assign({}, ...param);
// for (let item of param) {
// for (let [idx, val] of Object.entries(item)) {
// if (typeof val === 'object') {
// result[idx] = deepAssign(result[idx], val);
// }
// }
// }
// return result;
// }
function deepAssign(...sources) {
const result = {};
const stack = [{ target: result, sources }];
const map = new WeakMap();
while (stack.length) {
const { target, sources } = stack.pop();
for (const source of sources) {
if (source && typeof source === 'object') {
if (map.has(source)) {
let _key = map.get(source);
if (typeof _key == 'object') {
continue;
}
target[_key] = source;
continue; // 处理循环引用
}
map.set(source, target);
for (const [key, value] of Object.entries(source)) {
if (value && typeof value === 'object') {
if (map.has(value)) {
target[key] = map.get(value);
} else {
if (!target[key] || typeof target[key] !== 'object' || Array.isArray(target[key]) !== Array.isArray(value)) {
target[key] = Array.isArray(value) ? [] : {};
}
stack.push({
target: target[key],
sources: [target[key], value],
});
}
} else {
target[key] = value;
}
}
}
}
}
return result;
}
案例
var x = {
a: {
a1: {
a1_1: 1.1,
a1_2: 1.2
}
,a2: {
a2_1: 2.1,
a2_2: 2.2
}
},
b: 1
}
, y = {
a: {
a1: {
a1_3: 1.3
}
},
b: {
b1: {
b1_1: 1
},
b2: 555
},
c: 'ccc'
}
, z = {
b: {
b1: {
xx: 1,
yy: 2,
ccc: {
abb: '12242',
bbb: [1,2,3]
}
}
},
a: {
a55: {
xx: 33
}
}
}
console.log(deepAssign(x, y, z));