如何获得underscore.js数组对象键的总和? [英] How to get sum of an array object keys in underscore.js?

查看:117
本文介绍了如何获得underscore.js数组对象键的总和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数组:

var items = [
   {price1: 100, price2: 200, price3: 150},
   {price1: 10, price2: 50},
   {price1: 20, price2: 20, price3: 13},
]

我需要得到对象通过类似以下的所有键的总和:

I need to get object with sum of all keys like the following:

var result = {price1: 130, price2: 270, price3: 163};

我知道我可以只使用循环,但我正在寻找在下划线风格的方法:)

I know I may to use just loop but I'm looking for a approach in underscore style :)

推荐答案

不是很pretty,但我认为最快的方法是做这样

Not very pretty, but I think the fastest method is to do it like this

_(items).reduce(function(acc, obj) {
  _(obj).each(function(value, key) { acc[key] = (acc[key] ? acc[key] : 0) + value });
  return acc;
}, {});

或者,要真正过顶(我认为这将可以超过一个以上的速度更快,如果你使用的 lazy.js 而不是下划线):

Or, to go really over the top (I think it will can be faster than above one, if you use lazy.js instead of underscore):

_(items).chain()
  .map(function(it) { return _(it).pairs() })
  .flatten(true)
  .groupBy("0") // groups by the first index of the nested arrays
  .map(function(v, k) { 
    return [k, _(v).reduce(function(acc, v) { return acc + v[1] }, 0)]     
  })
  .object()
  .value()

这篇关于如何获得underscore.js数组对象键的总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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