通过唯一属性组合单个对象数组

时间:2017-08-24 09:52:17

标签: javascript arrays lodash arrayobject

我有一个对象数组,它基于一个唯一属性进行组合。 例如:

[
  { "macId": "123", "input": 30},
  { "macId": "567", "input": 40},
  { "macId": "123", "power": 100},
  { "macId": "567", "power": 250}
]

我希望得到的对象数组如下:

[
  { "macId": "123", "input": 30, "power": 100},
  { "macId": "567", "input": 40 "power": 250}
]

这可以用 lodash 吗?如果没有,我怎么能为此编写一个简短的代码呢?

4 个答案:

答案 0 :(得分:2)

使用lodash我会尝试使用macId groupBy,然后使用merge“组合”结果数组中的对象。

const after = 
  _(before)
    .groupBy('macId')
    .map(group => _.merge(...group))
    .value();

答案 1 :(得分:1)

我建议将ES6 MapObject.assign结合使用:



const arr = [
    { "macId": "123", "input": 30},
    { "macId": "567", "input": 40},
    { "macId": "123", "power": 100},
    { "macId": "567", "power": 250}
]

const result = [...arr.reduce((acc, obj) =>
    acc.set(obj.macId, Object.assign(acc.get(obj.macId) || {}, obj)), new Map).values()];

console.log(result);

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




答案 2 :(得分:0)

您可以使用Object#assignArray#find执行以下操作:

var myMergedArray = arr.reduce((acc = [], val) => {
  if (acc.filter(obj => obj.macId === val.macId).length !== 0) {
    Object.assign(acc.find((el) => el.macId === val.macId), val)
  } else {
    acc.push(val);
  }
  return acc;
}, [])

摘录:



var arr = [
  { "macId": "123", "input": 30},
  { "macId": "567", "input": 40},
  { "macId": "123", "power": 100},
  { "macId": "567", "power": 250}
]

var myMergedArray = arr.reduce((acc = [], val) => {
  if (acc.filter(obj => obj.macId === val.macId).length !== 0) {
    Object.assign(acc.find((el) => el.macId === val.macId), val)
  } else {
    acc.push(val);
  }
  return acc;
}, [])

console.log(myMergedArray);




答案 3 :(得分:0)

由于您已标记lodash,因此您可以轻松地对其进行分组并将其映射回来(使用reduce或_.merge合并)。

var arr = [
  { "macId": "123", "input": 30},
  { "macId": "567", "input": 40},
  { "macId": "123", "power": 100},
  { "macId": "567", "power": 250}
]

var unique = _.chain(arr).groupBy('macId').map(v => _.merge(...v)).value();

console.log(unique)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>