如何将多个对象合并/合并到数组中

时间:2019-12-18 11:08:08

标签: javascript arrays dictionary object arrayobject

im寻找将对象合并到数组中的最佳方法。 这是我的问题:

Object {
  "payload": Array [
    Object {
      "category": "kontrakan",
    },
    Object {
      "Tenant": "anji",
    },
  ],
  "type": "GET_DATA_VENUE_SUCCESS",
}

Object {
  "payload": Array [
    Object {
      "category": "kost",
    },
    Object {
      "Tenant": "ade",
    },
  ],
  "type": "GET_DATA_VENUE_SUCCESS",
} 

期望这样的变换:

{
  [
   {"category" : "kontrakan","Tenant" : "anji"}, 
   {"category" : "kost", "Tenant" : "ade"}
  ]
}

此处的代码:

let obj = doc.data();
let arrObj = _.map(_.keys(obj), key => ({ [key]: obj[key] }));
console.log(arrObj);

im已经尝试使用其他解决方案。 object.assign / key,lodash:_.merge,联合仍然无法正常工作...

3 个答案:

答案 0 :(得分:1)

您可以结合使用map方法和reduceObject.assign来合并objects properties

var arr = [{ "payload": [ { "category": "kontrakan", }, { "Tenant": "anji", } ], "type": "GET_DATA_VENUE_SUCCESS", }, { "payload": [ { "category": "kost", }, { "Tenant": "ade", }, ], "type": "GET_DATA_VENUE_SUCCESS", }]

var result = arr.map(({payload}) => payload.reduce((obj, item) => Object.assign(obj, item), {}));
console.log(result);

答案 1 :(得分:1)

您要寻找的功能是reduce

您可以使用reduce将“有效载荷”数据组合到单个对象中。通过使用对象作为累加器。

示例:

const a = {
  payload: [{
    category: 'a'
  },
  {
    tenant: 'a'
  }]
};


function mergePayload(obj) {
  return obj.payload.reduce((newObj, payloadObj) => {
    // Create a new object with the properties of the old and the new combined
    return Object.assign(newObj, payloadObj);
  }, {});
}

// {category: "a", tenant: "a"}
console.log(mergePayload(a))

您可以将带有数据的数组映射到化简器:

const data = [a, a];

// [{category: "a", tenant: "a"}, {category: "a", tenant: "a"}]
console.log(data.map((d) => mergePayload(d)));

编辑: 您可以缩短缩减时间,但这将不再为评论留出空间。

function mergePayload(obj) {
  return obj.payload.reduce((newObj, payloadObj) => Object.assign(newObj, payloadObj), {})
}

答案 2 :(得分:0)

假设数组中只有两个对象,并且可能的属性为“类别”和“租户”

let arr = [{  "payload": [{      "category": "kontrakan",    },    {      "Tenant": "anji",    },  ],  "type": "GET_DATA_VENUE_SUCCESS"}, {  "payload": [{      "category": "kost",    },    {      "Tenant": "ade",    },  ],  "type": "GET_DATA_VENUE_SUCCESS"}],
    result = arr.map(({payload: [{category: category}, {Tenant: tenant}]}) => ({category, tenant}));

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