我有一个这样的集合:
{
"2.2": {
"BALL":{"white":9,"black":11,"red":4},
"BAG":{"white":2,"black":11,"red":1},
"COVER":{"white":3,"black":8,"red":1}
},
"2.3": {
"BALL":{"white":1,"black":0,"red":7},
"BAG":{"white":3,"black":0,"red":0},
"COVER":{"white":9,"black":2,"red":28}
}
}
我想计算“2.2”和“2.3”的颜色总和(白色、黑色、红色)。
输出 所需的输出应该是这样的:
{
"2.2": {"white": 14, "black": 30, "red": 6},
"2.3": {"white": 13, "black": 2, "red": 35}
}
我尝试使用 underscore
.map
函数,但我无法正确理解它。任何人都可以帮忙。 ?
PS:需要一个仅使用 underscore.js 的解决方案。
最佳答案
这是 underscore.js
解决方案。
_.mapObject(collections, function(collection) {
return _.reduce(collection, function(memo, col) {
// credit: Bergi on http://stackoverflow.com/a/17350790/1465828
// the following line reads:
// for (var p in col) => loop all properties in col
// memo[p] = ... => assign memo[p] as ...
// (p in memo ? memo[p] : 0) => IF property p exists in memo, then memo[p], otherwise 0
// + col[p] => add col's p
for (var p in col) { memo[p] = (p in memo ? memo[p] : 0) + col[p]; }
return memo;
}, {});
});
关于javascript - 如何求key的值之和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30341930/