我有一个对象数组,其中包含一个poll的结果,它看起来(例如)像这样:
[
{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 }
]
基本上,我想循环并总结每个optionid / title的点。所以cat = 5,dog = 8,pig = 4.有没有办法在JavaScript中执行此操作?到目前为止我的所有尝试都失败了。我是自学成才的,只是一个初学者,所以解决方案越不复杂就越好。
答案 0 :(得分:0)
使用reduce
非常容易
var arr = [{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 }]
var result = arr.reduce(function(acc, v) {
acc[v.title] = (acc[v.title] || 0) + v.points
return acc
}, {})
console.log(result)
答案 1 :(得分:0)
使用reduce
div { height: 0px;
opacity: 0;
transition: opacity 0.5s; }
.active { height: 100%;
opacity: 1;
transition: opacity 0.5s; }
答案 2 :(得分:0)
我认为使用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)