Nodejs - Return 键值对数组,通过添加具有相同键的值

Nodejs - Return array of key-value pair by adding values with same key

我有以下对象数组:

const list = [
  {points: 3, name:'bob'},
  {points: 1, name:'john'},
  {points: 5, name:'john'},
  {points: 2, name:'john'},
  {points: 8, name:'john'},
  {points: 0, name:'bob'},
  {points: 2, name:'bob'},
  {points: 1, name:'bob'},
]

我想结束并反对 returns 包含每个名称的点总和的数据集列表,例如:

const list2 = [
  {name: 'bob', points: 6}, // sum of all of bob's points
  {name: 'john', points: 16}
]

我需要这个以便我可以使用生成的数据集生成折线图。

有没有办法做到这一点,最好使用 ramda.js

这是 Array.prototype.reduce() and Object.keys() 的一个相当简单的用法:

const list = [
  {points: 3, name:'bob'},
  {points: 1, name:'john'},
  {points: 5, name:'john'},
  {points: 2, name:'john'},
  {points: 8, name:'john'},
  {points: 0, name:'bob'},
  {points: 2, name:'bob'},
  {points: 1, name:'bob'},
]

const map = list.reduce((prev, next) => {
  // if the name has not already been observed, create a new entry with 0 points
  if (prev[next.name] == null) {
    prev[next.name] = 0;
  }

  // add the new points
  prev[next.name] += next.points;

  return prev;
}, {});

// map is now an object containing { [name]: [points] }
// convert this back into an array of entries
const list2 = Object.keys(map)
  .map(name => ({ name, points: map[name] }));

console.log(list2)
// [ { name: 'bob', points: 6 }, { name: 'john', points: 16 } ]

你可以这样做:

var combine = pipe(
  groupBy(prop('name')), //=> {bob: [bob_obj_1, bob_obj_2, ...], john: [ ... ]}
  map(pluck('points')),  //=> {bob: [3, 0, 2, 1], john: [1, 5, 2, 8]}
  map(sum)               //=> {bob: 6, john: 16}
)

或者您可以使用 reduce,但我认为这样更简单。

更新:我看错了输出格式。这修复了它:

var combine = pipe(
  groupBy(prop('name')), //=> {bob: [bob_obj_1, bob_obj_2, ...], john: [ ... ]}
  map(pluck('points')),  //=> {bob: [3, 0, 2, 1], john: [1, 5, 2, 8]}
  map(sum),              //=> {bob: 6, john: 16}
  toPairs,               //=> [["bob", 6], ["john", 16]]
  map(zipObj(['name', 'points'])) //=> [{name: "bob", points: 6}, 
                         //             {name: "john", points: 16}]
)