因此,我有一个名为playerscoresdata
的对象数组,我需要获得每个球员的得分和犯规总数。
我的问题是我认为我使用了太多的迭代/循环
有没有更干净的解决方案?
null
const playerScoresData = [
{
playerId: '1',
score: 20,
foul: 3
},
{
playerId: '1',
score: 5,
foul: 2
},
{
playerId: '2',
score: 30,
foul: 1
},
{
playerId: '2',
score: 10,
foul: 3
}
]
const main = () => {
let stats = []
let newData = {}
const uniqPlayerIds = [...new Set(playerScoresData.map(item => item.playerId))]
for (var x = 0; x < uniqPlayerIds.length; x++) {
newData = {
playerId: uniqPlayerIds[x],
totalScores: 0,
totalFouls: 0
}
let filteredData = playerScoresData.filter(data => data.playerId === uniqPlayerIds[x])
for (var y = 0; y < filteredData.length; y++) {
newData.totalScores += filteredData[y].score
newData.totalFouls += filteredData[y].foul
}
stats.push(newData)
}
return stats
}
console.log(main())
null
您可以简单地使用.reduce()
方法,以更方便的方式聚合数据:
null
const playerScoresData = [
{
playerId: '1',
score: 20,
foul: 3
},
{
playerId: '1',
score: 5,
foul: 2
},
{
playerId: '2',
score: 30,
foul: 1
},
{
playerId: '2',
score: 10,
foul: 3
}
];
const result = playerScoresData.reduce((acc, item) => {
acc[item.playerId] = acc[item.playerId] || {tScore:0, tFoul: 0}; // set default value if missing
acc[item.playerId].tScore += item.score;
acc[item.playerId].tFoul += item.foul;
return acc;
}, {});
console.log(result);