![](/img/trans.png)
[英]How to sort an object array by multiple keys in javascript using _.sortBy() method of Javascript Underscore.js?
[英]How to get sum of an array object keys in underscore.js?
我有以下数组:
var items = [
{price1: 100, price2: 200, price3: 150},
{price1: 10, price2: 50},
{price1: 20, price2: 20, price3: 13},
]
我需要获得所有键的总和,如下所示:
var result = {price1: 130, price2: 270, price3: 163};
我知道我可能只使用循环,但我正在寻找下划线风格的方法:)
不是很漂亮,但我认为最快的方法就是这样做
_(items).reduce(function(acc, obj) {
_(obj).each(function(value, key) { acc[key] = (acc[key] ? acc[key] : 0) + value });
return acc;
}, {});
或者,真正超越顶部(我认为它会比上面的更快,如果你使用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()
对于聚合,我建议reduce
:
_.reduce(items, function(acc, o) {
for (var p in acc) acc[p] += o[p] || 0;
return acc;
}, {price1:0, price2:0, price3:0});
或更好
_.reduce(items, function(acc, o) {
for (var p in o)
acc[p] = (p in acc ? acc[p] : 0) + o[p];
return acc;
}, {});
来自地狱的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(', '));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.