我有包含season
和fielding
数组的数据。 fielding
数组具有3个参数Catches
,Runouts
,Stumpings
。我想计算总计Catches
,Stumpings
,Runouts
。
var data = [
{
season:2015,
fielding:{Catches:2, Runouts:1, Stumpings:1
},
{
season:2016,
fielding:{Catches:0, Runouts:1, Stumpings:1
},
{
season:2016,
fielding:{Catches:0, Runouts:0, Stumpings:0
},
{
season:2017,
fielding:{Catches:1, Runouts:3, Stumpings:1
},
{
season:2017,
fielding:{Catches:2, Runouts:1, Stumpings:2
}
]
我希望最终输出作为对象,如下所示:
Catches -> 2+0+0+1+2 = 5
Runouts -> 1+1+0+3+1 = 6
Stumpings -> 1+1+0+1+2 =5
我尝试过的事情:
let dismissals = data.reduce( (a,{season, fielding}) => {
if(!a[fielding.Catches]){
a[fielding.Catches] = {};
}else if(a[fielding.Runouts]){
a[fielding.Runouts] = {};
}else if(a[fielding.Stumpings]){
a[fielding.Stumpings] = {};
}else{
a[fielding.Stumpings] += 1;
a[fielding.Runouts] += 1;
a[fielding.Catches] += 1;
}
return a;
}, {});
我的代码未计算所需的输出,而是给出了NaN
。
答案 0 :(得分:4)
遍历fielding
的项,然后将值添加到累加器的[key]中(如果该键尚不存在,则默认为0
) :
var data=[{season:2015,fielding:{Catches:2,Runouts:1,Stumpings:1}},{season:2016,fielding:{Catches:0,Runouts:1,Stumpings:1}},{season:2016,fielding:{Catches:0,Runouts:0,Stumpings:0}},{season:2017,fielding:{Catches:1,Runouts:3,Stumpings:1}},{season:2017,fielding:{Catches:2,Runouts:1,Stumpings:2}}];
console.log(
data.reduce((a, { fielding }) => {
Object.entries(fielding).forEach(([key, val]) => {
if (key !== '_id') a[key] = (a[key] || 0) + val;
});
return a;
}, {})
);
答案 1 :(得分:2)
您可以使用减少并循环fielding
的Object.keys
const res = data.reduce((a, {fielding}) =>
Object.keys(fielding).forEach(f => a[f] = (a[f] || 0) + fielding[f]) || a
, Object.create(null));
console.log(res);
<script>
var data = [
{
season:2015,
fielding:{Catches:2, Runouts:1, Stumpings:1}
},
{
season:2016,
fielding:{Catches:0, Runouts:1, Stumpings:1}
},
{
season:2016,
fielding:{Catches:0, Runouts:0, Stumpings:0}
},
{
season:2017,
fielding:{Catches:1, Runouts:3, Stumpings:1}
},
{
season:2017,
fielding:{Catches:2, Runouts:1, Stumpings:2}
}
];
</script>