我有一个包含民意调查结果的对象数组,它看起来(例如)如下所示:
[
{title: 'cat', optionid: 7, points: 1 },
{title: 'cat', optionid: 7, points: 3 },
{title: 'cat', optionid: 7, points: 1 },
{title: 'dog', optionid: 8, points: 3 },
{title: 'dog', optionid: 8, points: 2 },
{title: 'dog', optionid: 8, points: 3 },
{title: 'pig', optionid: 9, points: 2 },
{title: 'pig', optionid: 9, points: 1 },
{title: 'pig', optionid: 9, points: 1 }
]
基本上,我想循环遍历并总结每个选项ID/标题的分数。所以 cat = 5,dog = 8,pig = 4。有没有办法在 JavaScript 中做到这一点?到目前为止我所有的尝试都失败了。我是自学成才的,只是一个初学者,所以解决方案越简单越好。
最佳答案
我认为使用reduce
是最好的方法。然而,对于像我这样的新手来说,这可能会令人困惑。所以这里有一个更直接的方法。希望这更容易理解。
var animals = [{title: 'cat', optionid: 7, points: 1 },
{title: 'cat', optionid: 7, points: 3 },
{title: 'cat', optionid: 7, points: 1 },
{title: 'dog', optionid: 8, points: 3 },
{title: 'dog', optionid: 8, points: 2 },
{title: 'dog', optionid: 8, points: 3 },
{title: 'pig', optionid: 9, points: 2 },
{title: 'pig', optionid: 9, points: 1 },
{title: 'pig', optionid: 9, points: 1 }];
// create new object to store results in
newObj = {};
// loop through animal objects
animals.forEach(function(animal){
// check if animal type has already been added to newObj
if(!newObj[animal.title]){
// If it is the first time seeing this animal type
// we need to add title and points to prevent errors
newObj[animal.title] = {};
newObj[animal.title]['points'] = 0;
}
// add animal points to newObj for that animal type.
newObj[animal.title]['points'] += animal.points
})
console.log(newObj)
关于javascript - 循环遍历对象数组并返回某些值的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48738827/