根据键将两个对象合并为一个对象

时间:2019-03-26 07:07:22

标签: javascript

我有两个如下所示的对象,我想基于键将它们合并

let Object1 = {
                "b":"test1",
                "a":"test3",
                "type":"sample1"
              }
let Object2=  {
                "b":{
                  "endDate":"ddd1",
                  "startDate":"dd01"
                },
                "a":{
                  "endDate":"31",
                  "startDate":"01"
                },
                "type":"sample2"
              }

预期结果应如下所示

let Object3 = {
                "b":{
                  "endDate":"ddd1",
                  "startDate":"dd01",
                  "XYZ":"test1"
                },
                "a":{
                  "endDate":"31",
                  "startDate":"01",
                  "XYZ":"test3"
                },
              }

任何人都可以帮助使用JavaScript或loadash功能

2 个答案:

答案 0 :(得分:0)



可以这么简单:

let Object1 ={"b":"test1","a":"test3","type":"sample1"};let Object2 ={"b":{"endDate":"ddd1","startDate":"dd01"},"a":{"endDate":"31","startDate":"01"},"type":"sample2"}

let Object3 = Object2;
for (let i in Object3){
  Object3[i]["XYZ"] = Object1[i]
}
Object3["type"] = "12345"
console.log(Object3)

答案 1 :(得分:0)

您可以使用rest运算符删除type属性,然后将第一个对象的值分配给合并对象的新属性

let mergeObjects = (a, b) => {

    let {type, ...rest} = b; //remove type property
    for(let prop in rest){
        if(a[prop]){
            rest[prop].xyz = a[prop]; 
        }
    }
    return rest;
}

let Object3= mergeObjects(Object1, Object2);
console.log(Object3);