我有一个这样的集合:
{
"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需要解决方案。
答案 0 :(得分:1)
尝试:
var obj = {
"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
}
}
}
var w = 0;
for(var i in obj){
for(var j in obj[i]){
w +=obj[i][j]['white'];
}
}
<强>更新强>
var obj = {
"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
}
}
}
for (var i in obj) {
var tmp = {
white: 0,
black: 0,
red: 0
};
for (var j in obj[i]) {
tmp['white'] += obj[i][j]['white'];
tmp['black'] += obj[i][j]['black'];
tmp['red'] += obj[i][j]['red'];
}
obj[i] = tmp
}
console.log(obj);
答案 1 :(得分:1)
以下是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;
}, {});
});