输入:
var data = [
{ team: 'A', score: 80, year: 2009 },
{ team: 'A', score: 180, year: 2009 },
{ team: 'A', score: 80, year: 2010 },
{ team: 'B', score: 80, year: 2009 },
{ team: 'B', score: 80, year: 2010 },
];
输出:
{
2009: {
A: 260,
B: 80,
},
2010: {
A: 80,
B: 80,
},
};
答案 0 :(得分:2)
一种可能的解决方案是以这种方式使用Array.reduce():
var data = [{team: 'A', score: 80, year: 2009},{team: 'A', score: 180, year: 2009}, {team: 'A', score: 80, year: 2010}, {team: 'B', score: 80, year: 2009}, {team: 'B', score: 80, year: 2010}];
// We use reduce starting with an "accumulator" equal to an empty object.
// On every iteration of "reduce", you have access to the "accumulator" and
// the current inspected element of the array (an "object"). We also use
// "destructuring" on the current inspected object.
let res = data.reduce((acc, {year, team, score}) =>
{
// If the value hold by property "year" is not a defined property on the
// "acc", then set it to be an empty object.
acc[year] = acc[year] || {};
// If the value hold by property "team" is not a defined property on
// "acc[year]", then set it to be 0.
acc[year][team] = acc[year][team] || 0;
// Increment the accumulated score on "acc[year][team]". Note this will
// be "0", thanks to previous lines, if don't previously exists.
acc[year][team] += score;
// Return the altered "accumulator".
return acc;
}, {} /* This is the initial accumulator object */);
console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
答案 1 :(得分:0)
var data = [{team: 'A', score: 80, year: 2009},{team: 'A', score: 180, year: 2009}, {team: 'A', score: 80, year: 2010}, {team: 'B', score: 80, year: 2009}, {team: 'B', score: 80, year: 2010}]
var obj = {};
for (var i = 0; i < data.length; i++) {
if (obj[data[i].year]) {
var a = obj[data[i].year]['A'];
var b = obj[data[i].year]['B'];
obj[data[i].year] = {
A: data[i].team === 'A' ? a + data[i].score : a,
B: data[i].team === 'B' ? b + data[i].score : b,
}
} else {
obj[data[i].year] = {
A: data[i].team === 'A' ? data[i].score : 0,
B: data[i].team === 'B' ? data[i].score : 0,
}
}
}
console.log(obj)