javascript - 深度合并两个 javascript 对象 lodash/vanilla

标签 javascript lodash

我正在尝试将两个对象与包含对象合并..其中包含对象数组..你明白了。但是,我的代码没有产生期望的结果,我不明白为什么......可能是因为我刚刚开始使用 lodash 并且我错过了一些明显的东西

这是我要合并的两个对象

 var original = { 
    a: "bbbb", 
    Id: 1, 
    b: { 
        a: "bbb", 
        Id: 2 
    }, 
    c: "aaa",
    d: [
        { 
            a: "bbbb", 
            Id: 1, 
            b: { 
                a: "bbb", 
                Id: 2 
            }, 
            c: "aaa"
        },
        { 
            a: "bbbb", 
            Id: 2, 
            b: { 
                a: "bbb", 
                Id: 3 
            }, 
            c: "aaa" 
        }
    ] 
};

var source = { 
    a: "aaa", 
    Id: 1, 
    b: { 
        a: "aaa", 
        Id: 2 
    }, 
    c: null, 
    d: [
        { 
            a: "aaa", 
            Id: 1, 
            b: { 
                a: "aaa", 
                Id: 2 
            }, 
            c: null
        },
        { 
            a: "aaa", 
            Id: 2, 
            b: { 
                a: "aaa", 
                Id: 3 
            }, 
            c: null 
        }
    ] 
};

结果对象应该只包含“aaa”作为值,并且没有空值。(从“源”获取值,除非它为空并且不复制只是复制数组,而是合并其中的对象..)我的代码合并对象很好......但是,当它到达对象数组时,它无法产生正确的结果

结果应该是:

{"a":"aaa",
 "Id":1,
 "b":
    {
     "a":"aaa",
     "Id":2
    },
    "c":"aaa",
   "d":
     [
      {
       "a":"aaa",
       "Id":1,
        "b":
         {
         "a":"aaa",
         "Id":2
         },
        "c":"aaa"
     },

{ “a”:“aaa”, “身份证”:2, “b”: { “a”:“aaa”, “身份证”:3 }, “c”:“aaa” } ]}

这是我的代码:https://jsfiddle.net/yodfcn6e/

谢谢!

最佳答案

您可以迭代对象的键,并且仅当目标具有 null 值时才进行更新。

function update(source, target) {
    Object.keys(source).forEach(function (k) {
        if (target[k] === null) {
            target[k] = source[k];
            return;
        }
        if (source[k] && typeof source[k] === 'object') {
            update(source[k], target[k]);
        }
    });
}

var source = { a: "bbbb", Id: 1, b: { a: "bbb", Id: 2 }, c: "aaa", d: [{ a: "bbbb", Id: 1, b: { a: "bbb", Id: 2 }, c: "aaa" }, { a: "bbbb", Id: 2, b: { a: "bbb", Id: 3 }, c: "aaa" }] },
    target = { a: "aaa", Id: 1, b: { a: "aaa", Id: 2 }, c: null, d: [{ a: "aaa", Id: 1, b: { a: "aaa", Id: 2 }, c: null }, { a: "aaa", Id: 2, b: { a: "aaa", Id: 3 }, c: null }] };

update(source, target);

console.log(target);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 深度合并两个 javascript 对象 lodash/vanilla,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46202433/

相关文章:

javascript - Canvas 的缓进/缓出相机移动

javascript - 使用下划线确定对象是否存在于深度嵌套的对象数组中?

javascript - Lodash 递归函数超出最大堆栈大小

javascript - 有没有更优雅的 "fake"类继承方式?

javascript - 如何通过特定键合并数组中的项目?

javascript - 如何在 javascript 变量中设置 ckeditor html 数据

javascript - 未找到 Lodash 文件,但它在 index.html 中正确列出并且位于所描述的目录中

lodash - 通过嵌套数组中的匹配属性查找对象

javascript - 如何自动水平滚动无序列表?

javascript - 我动态创建了一个复选框,希望在提交表单之前验证该复选框