javascript 如何在 underscore.js 中获取数组对象键的总和?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17350454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 07:59:30  来源:igfitidea点击:

How to get sum of an array object keys in underscore.js?

javascriptbackbone.jsunderscore.js

提问by Erik

I have the following array:

我有以下数组:

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 :)

我知道我可能只使用循环,但我正在寻找一种下划线样式的方法:)

采纳答案by Artur Nowak

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;
}, {});

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

或者,要真正超越顶部(我认为它会比上面更快,如果你使用lazy.js而不是下划线):

_(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()

回答by Bergi

For aggregating I'd recommend reduce:

对于聚合,我建议reduce

_.reduce(items, function(acc, o) {
    for (var p in acc) acc[p] += o[p] || 0;
    return acc;
}, {price1:0, price2:0, price3:0});

Or better

或更好

_.reduce(items, function(acc, o) {
    for (var p in o)
        acc[p] = (p in acc ? acc[p] : 0) + o[p];
    return acc;
}, {});

回答by YD1m

Js from hell:

来自地狱的JS:

var names = _.chain(items).map(function(n) {  return _.keys(n);  }).flatten().unique().value();    
console.log(_.map(names, function(n) {              
      return  n + ': ' + eval((_.chain(items).pluck(n).compact().value()).join('+')); 
}).join(', '));  

jsfiddle

提琴手