我有一个对象数组:
console.log(quizNight[0].round[--latestRound].t)
-> [ { teamID: 16867, correctAnswers: 1 },
{ teamID: 16867, correctAnswers: 1 },
{ teamID: 16867, correctAnswers: 1 } ]
我希望有一个 correctTotalAnswers 数组看起来像这样:
[ { teamID: 16867, correctTotalAnswers: 3} ]
最明智的做法是什么?我现在拥有的代码:
let correctAnswersArrayRoung = quizNight[0].round[--latestRound].t;
let totalCorrentAnswersArray = [];
for (let correctAnswer in correctAnswersArrayRoung) {
console.log(correctAnswersArrayRoung[correctAnswer])
for(let element in totalCorrentAnswersArray){
if(element.teamID === correctAnswer.teamID){
element.totalCorrectAnswers = ++element.totalCorrectAnswers
} else {
totalCorrentAnswersArray.push({
teamID: correctAnswer.teamID,
totalCorrectAnswers: 1
})
}
}
}
console.log(totalCorrentAnswersArray)
返回 []
最佳答案
你可以这样使用reduce
(见内联注释):
// Your initial data
const initialArray = [
{ teamID: 16867, correctAnswers: 1 },
{ teamID: 16867, correctAnswers: 1 },
{ teamID: 16866, correctAnswers: 1 }
]
// Use reduce to loop through the data array, and sum up the correct answers for each teamID
let result = initialArray.reduce((acc, c) => {
// The `acc` is called "accumulator" and it is
// your object passed as the second argument to `reduce`
// We make sure the object holds a value which is
// at least `0` for the current team id (if it exists,
// it will be used, otherwise will be initialized to 0)
acc[c.teamID] = acc[c.teamID] || 0
// Sum up the correctAnswers value
acc[c.teamID] += c.correctAnswers
return acc
}, {}) // <- Start with an empty object
// At this point the result looks like this:
// {
// "16866": 1,
// "16867": 2
// }
// Finally convert the result into an array
result = Object.keys(result).map(c => ({
teamID: c,
correctAnswers: result[c]
}))
console.log(result);
关于javascript - 添加具有相同 ID 的对象的数组分数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49758781/