合并并减少Javascript对象以创建总计

时间:2018-04-20 12:55:57

标签: javascript lodash

我有一个对象数组,如下所示:

[
    {network: "linkedin", visits: 25}
    {network: "twitter", visits: 45}
    {network: "linkedin", visits: 26}
    {network: "twitter", visits: 27}
    {network: "facebook", visits: 235}
    {network: "twitter", visits: 744}
]

我想返回一个新数组,它结合了网络相同的访问次数,结果如下:

[
    {network: "linkedin", visits: 51}
    {network: "twitter", visits: 771}
    {network: "facebook", visits: 235}
]

我怎样才能在纯JS中做到这一点?我的项目还提供了Lodash库,它也可以提供解决方案。

编辑:重复问题中接受的答案对我有用。

1 个答案:

答案 0 :(得分:0)

const inputData = [
  {network: "linkedin", visits: 25},
  {network: "twitter", visits: 45},
  {network: "linkedin", visits: 26},
  {network: "twitter", visits: 27},
  {network: "facebook", visits: 235},
  {network: "twitter", visits: 744}
];

const outputData = inputData.reduce((currentArr, nextObj) => {
  return currentArr.reduce((curr, next) => (next.network === nextObj.network) || curr, false)
    ? currentArr.map((val) => val.network === nextObj.network 
      ? Object.assign({}, val, { visits: val.visits + nextObj.visits }) 
      : val
    )
    : [].concat(currentArr, nextObj);
}, []);

console.log(outputData);