js 深度合并对象(Object.assign)

// 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));

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值