如何将两个对象对象合并为一个对象

时间:2018-06-02 23:42:47

标签: javascript ecmascript-6

如何将两个对象对象合并为一个对象?

实施例

let obj1 = {monkey:{size: 120, color: "black"}, cat: {size: 30, color: "gray"}}

let obj2 = {monkey:{country: "africa", test: "test"}, cat: {country: "all", testCat: "testCat"}}

输出应为:

{monkey:{size: 120, color: "black", country: "africa", test: "test"}, cat: {size: 30, color: "gray", country: "all", testCat: "testCat"}}

我不知道有多少动物在那里。

类似这样的事情

let merged = {...obj1, ...obj2}

1 个答案:

答案 0 :(得分:0)

我们需要知道有多少Object要合并,所以我将它们分组在一个数组中。

这个解决方案可能看起来很糟糕但是有效:)



let obj1 = {
  monkey: {
    size: 120,
    color: "black"
  },
  cat: {
    size: 30,
    color: "gray"
  }
};

let obj2 = {
  monkey: {
    country: "africa",
    test: "test"
  },
  cat: {
    country: "all",
    testCat: "testCat"
  }
};

let objects = [obj1, obj2];
let output = {};



objects.map(function(obj) {
  var keys = Object.keys(obj);
  keys.map(function(key) {
    if (!output[key])
      output[key] = obj[key];
    else {
      var keyss = Object.keys(obj[key]);
      keyss.map(function(item) {
        output[key][item] = obj[key][item];
      });
    }
  });
});



console.log(output);




使用箭头功能优化。

objects.map(obj =>Object.keys(obj).map(key => output[key] ?  Object.keys(obj[key]).map( item =>output[key][item] = obj[key][item] ) : output[key] = obj[key] ));