javascript - 循环遍历对象数组并返回某些值的总和

标签 javascript arrays javascript-objects

我有一个包含民意调查结果的对象数组,它看起来(例如)如下所示:

[
    {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/

相关文章:

javascript - JQGrid 在列排序时丢失记录

javascript - 将 Pikachoose 设置为仅显示缩略图

javascript - AJAX 不适用于 Knockout.JS

c - 如何在 C 中连接两个动态 int 数组?

javascript - 如何在其他对象数组的每个值上创建多个数组?

javascript - VUE引擎如何评估属性代码?

java - 尝试创建一个可以调用 5 次的随机数组,并且可以根据用户输入进行测试

c - 如何在C中将数组拆分为两个数组

javascript - 从另一个对象创建对象数组

原型(prototype)中具有数字属性的 Javascript 对象