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

查看:27
本文介绍了如何在 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 :)

推荐答案

不是很漂亮,但我觉得最快的方法是这样做

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天全站免登陆