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

时间:2017-09-13 16:20:03

标签: 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"作为值而没有空值。(取值来自" source",除非它为null并且不复制只复制数组,而是合并其中的对象..)我的代码合并对象就好了...但是,当它到达对象数组时,它无法产生正确的结果

结果应为:

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

{            "":" AAA&#34 ;,            "标识":2,             " B&#34 ;:              {              "":" AAA&#34 ;,              "标识":3              },             " C":" AAA"          } ]}

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

谢谢你!

1 个答案:

答案 0 :(得分:1)

您可以迭代对象的键,并仅在目标具有google_profile_res_body值时才更新。



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




相关问题