减少键上的对象数组并将值求和成数组 [英] Reduce array of objects on key and sum value into array

查看:88
本文介绍了减少键上的对象数组并将值求和成数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下对象:

data = [
  { name: 'foo', type: 'fizz', val: 9 },
  { name: 'foo', type: 'buzz', val: 3 },
  { name: 'bar', type: 'fizz', val: 4 },
  { name: 'bar', type: 'buzz', val: 7 },
];

使用过的lodash地图:

And used lodash map:

result = _.map(data, function item, idx){
  return {
    key: item[key],
    values: item.value,
  }
}

这将导致:

[
  { key: foo, val: 9 },
  { key: foo, val: 3 },
  { key: bar, val: 4 },
  { key: bar, val: 7 },
]

但是现在我要返回:

[
  { key: 'foo', val: 12 },
  { key: 'bar', val: 11 },
]

我尝试使用reduce似乎只输出到单个对象,然后可以将其转换回数组,但是我觉得必须有一种优雅的方法来使用lodash将源数据直接转换为所需的数据没有所有中间步骤的结果.

I tried using reduce which seems to only output to a single object, which I could then convert back into an array, but I feel like there must be an elegant way to use lodash to go from my source data straight to my desired result without all of the intermediate steps.

我认为解决了我的确切问题,但似乎不得不将对象转换为上面概述的所需对象数组,需要做很多工作.

I thought this was addressing my exact problem, but it seems like quite a bit of work just to have to convert the object into the desired array of objects outlined above.

干杯.

推荐答案

有趣的是,由于想要通过键累积值,但是又希望将键作为属性键的值,因此并非一帆风顺.所以有点像逆映射减少:

Interestingly not straight forward, because of wanting to accumulate the value by key, but then wanting the key as a value of the property key. So somewhat like an inverse map reduce:

var result = 
    _.chain(data)
        .reduce(function(memo, obj) {
            if(typeof memo[obj.name] === 'undefined') {
                memo[obj.name] = 0;
            } 
            memo[obj.name] += obj.val;
            return memo;
        }, {})
        .map(function (val, key) {
            return {key: key, val: val};
        })
        .value();

为了简洁起见,在es6中:

For the sake of brevity in es6:

_.chain(data)
    .reduce((memo, obj) => {
        memo[obj.name = obj.val] += obj.val;
        return memo; 
    }, {})
    .map((val, key) => ({key, val}))   
    .value();

这篇关于减少键上的对象数组并将值求和成数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆