查找对象数组中所有对象的所有数值的总和

时间:2015-12-29 12:43:48

标签: javascript arrays lodash

我有一个像这样的对象数组:

 data: [
        a:[
            {keyone:'a', keytwo: 'anna', keythree: 23, keyfour: 15},
            {keyone:'a', keytwo: 'anna', keythree: 23, keyfour: 15},
            {keyone:'a', keytwo: 'anna', keythree: 23, keyfour: 15},
            {keyone:'a', keytwo: 'anna', keythree: 23, keyfour: 15}
        ]
    ]

我想首先找到所有具有数值的键,然后将它们相加并使用键创建一个新对象,并将sum作为它的值。

结果应该是:

sums = { keythree: 92, keyfour: 60 }

我正在使用Lodash。这就是我现在所处的位置:

//Get all group names
    var keys = Object.keys(data);

    //Do this for all groups
    for(var i = 0; i< keys.length; i++) {
        //For all user records in the group
        _u.forEach(data[keys[i]], function(item) {
            //Find those keys which have a numeric value
            var numKeys = Object.keys(_u.pick(item, _u.isNumber));

            //For each of these keys, calculate the sum
            _u(numKeys).forEach(function(n) {
                _u.set(sums, n+'['+keys[i]+']', _u.sum(_u.map(data[keys[i]], n)));
            }).value();
        });
    }

这样可行,我得到了预期的结果。但我正在尝试减少循环并使其更有效。我认为Lodash有一种方法可以更好地完成它,但文档很难通过。

2 个答案:

答案 0 :(得分:2)

试试这个

&#13;
&#13;
var data = {
  a: [
    { keyone:'a', keytwo: 'anna', keythree: 23, keyfour: 15 },
    { keyone:'a', keytwo: 'anna', keythree: 23, keyfour: 15 },
    { keyone:'a', keytwo: 'anna', keythree: 23, keyfour: 15 },
    { keyone:'a', keytwo: 'anna', keythree: 23, keyfour: 15 }
  ],
  
  b: [
    { keyone:'b', keytwo: 'any', keythree: 10, keyfour: 100 },
    { keyone:'b', keytwo: 'any', keythree: 10, keyfour: 100 },
    { keyone:'b', keytwo: 'any', keythree: 10, keyfour: 100 },
    { keyone:'b', keytwo: 'any', keythree: 10, keyfour: 100 }
  ]
};

var result = _.mapValues(data, function (e) {
  return _.reduce(e, function (prev, current) {
    return _(current)
      .pick(_.isNumber)
      .mapValues(function (value, key) {
         return (prev[key] || 0) + value;
      })
      .value();
  }, {});
});

console.log( result );
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

这是一种使用reduce()的方法:

_.reduce(data, function(result, item) {
    return _.merge(result, _.pick(item, _.isFinite), _.add);
}, {});

每次迭代都使用merge()来更新reduce累加器。我们可以使用pick() + isFinite(),以便只合并数字值。 add()函数为给定的键值添加两个值。这是merge()的自定义函数。