[英]Loop through array of objects and return sum of certain values
我有一个包含轮询结果的对象数组,(例如)如下所示:
[
{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 /标题的要点。 所以cat = 5,dog = 8,pig =4。在JavaScript中有没有办法做到这一点? 到目前为止,我所有的尝试都以失败告终。 我是自学成才的,只是一个初学者,所以解决方案越简单越好。
用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)
使用减少
let data = [ { 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 } ]; let result = data.reduce((re, obj) => { let index = re.map(o => o.optionid).indexOf(obj.optionid); index > -1 ? re[index].points += obj.points : re.push(obj); return re; }, []); console.log(result);
我认为使用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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.