如何使用 Ramda 按值对键和组求和?

How do I sum a key and group by value using Ramda?

我有这样的数据:

const items = [
  {category: 'food', amount: 5},
  {category: 'food', amount: 5},
  {category: 'transport', amount: 2},
  {category: 'travel', amount: 11},
  {category: 'travel', amount: 1},
]

如何对 amount 求和并按每个 category 进行分组,得到:

{
  food : 10,
  transport : 2,
  travel : 12,
}

您可以使用 reduceBy:

R.reduceBy((acc, next) => acc + next.amount, 0, R.prop('category'))(items);

使用 reduceBy 可能是个好主意。如果您觉得有用,这里有一个替代方案。

itemize 函数开始:

const itemize = ({category: c, amount: a}) => ({[c]: a});

itemize({category: 'food', amount: 5});
//=> {food: 5}

然后定义一个可以添加或合并项目的函数:

const additem = mergeWith(add);

additem({food: 5}, {food: 5});
//=> {food: 10}

additem({food: 5}, {transport: 2});
//=> {food: 5, transport: 2}

最后在reducer中使用这两个函数:

reduce((a, b) => additem(a, itemize(b)), {}, items);