Javascript ES6:对象的Groupby和求和数组

时间:2018-11-18 07:28:44

标签: javascript ecmascript-6

我想对嵌套数组中属于某个组的所有值求和(例如100、101、102 ...)

我知道周围有一些解决方案,但是区别在于我的嵌套数组的字典结构不是{key:100,value:0},{key:101,value:0}

输入:

{
  {key: "person1"
   values:
   [{100.0: 0, 101.0: 0, 102.0: 0, 103.0: 0, 104.0: 0},
    {100.0: 0, 101.0: 0, 102.0: 4, 103.0: 18, 104.0: 12},
    {100.0: 2, 101.0: 0, 102.0: 0, 103.0: 1, 104.0: 0},
    {100.0: 2, 101.0: 1, 102.0: 7, 103.0: 14, 104.0: 21},
    {100.0: 0, 101.0: 0, 102.0: 0, 103.0: 0, 104.0: 0}]
  }
  {key: "person2"
   values:
  [{100.0: 5, 101.0: 0, 102.0: 0, 103.0: 0, 104.0: 0},
   {100.0: 5, 101.0: 0, 102.0: 4, 103.0: 18, 104.0: 12},
   {100.0: 5, 101.0: 0, 102.0: 0, 103.0: 1, 104.0: 0},
   {100.0: 5, 101.0: 1, 102.0: 7, 103.0: 14, 104.0: 21},
   {100.0: 5, 101.0: 0, 102.0: 0, 103.0: 0, 104.0: 0}]
  }
}

预期输出:

{
[key: "person1"
 values: {100.0: 4, 101.0: 5, 102.0: 11, 103.0: 23, 104.0: 33}]
[key: "person2"
values: {100.0: 20, 101.0: 5, 102.0: 11, 103.0: 23, 104.0: 22}]
}

1 个答案:

答案 0 :(得分:0)

给定一个对象数组,您可以map()遍历该数组。然后在map() reduce()的每次迭代中,将值的数组向下求和:

let arr = [
  {
  key: "person1",
  values:[
  {100.0: 0, 101.0: 0, 102.0: 0, 103.0: 0, 104.0: 0},
  {100.0: 0, 101.0: 0, 102.0: 4, 103.0: 18, 104.0: 12},
  {100.0: 2, 101.0: 0, 102.0: 0, 103.0: 1, 104.0: 0},
  {100.0: 2, 101.0: 1, 102.0: 7, 103.0: 14, 104.0: 21},
  {100.0: 0, 101.0: 0, 102.0: 0, 103.0: 0, 104.0: 0}
  ]
},
{
  key: "person2",
  values:[
  {100.0: 5, 101.0: 0, 102.0: 0, 103.0: 0, 104.0: 0},
  {100.0: 5, 101.0: 0, 102.0: 4, 103.0: 18, 104.0: 12},
  {100.0: 5, 101.0: 0, 102.0: 0, 103.0: 1, 104.0: 0},
  {100.0: 5, 101.0: 1, 102.0: 7, 103.0: 14, 104.0: 21},
  {100.0: 5, 101.0: 0, 102.0: 0, 103.0: 0, 104.0: 0}
  ]
  }
]

let sums = arr.map(({key, values}) => {
  return {
    key,
    values: values.reduce((sums, obj) => {
      Object.keys(obj).forEach(k => sums[k] += obj[k] )
      return sums
    })
  }
})
console.log(sums)

如果小数位很重要,则应在you数组中的键周围加上引号。否则,它们将转换为字符串并失去小数位数。