所以,我有这样的事情:
objArray1 = [ { candidate1: "Alex" , votes: 4}, { candidate2: "Paul", votes: 3}];
objArray2 = [ { candidate1: "Alex" , votes: 7}, { candidate2: "Ben", votes: 3}, { candidate3: "Melisa", votes:8 }];
我正在尝试使用 javascript 为所有候选人创建一个数组,并查看他们每个人有多少票。计算选票的部分很容易,但我不知道如何将所有候选人放在一个数组中。
我应该得到一个数组:Alex、Paul、Ben 和 Melisa。
谢谢!
var candidates = [];
var found = 0;
for(var i=0;objArray1.length>i;i++){
found = 0;
//add votes to candidate array
for(var j=0;candidates.length>j;j++){
if(candidates[j].name==objArray1[i][Object.keys(objArray1[i])[0]]){
candidates[j].votes = candidates[j].votes+objArray1[i].votes;
found = 1;
}
}
//if condidate not found in votes array, create new
if(found==0){
var tmp = {};
tmp.name = objArray1[i].candidate;
tmp.votes = objArray1[i].votes;
//add to array
candidates.push(tmp);
}
}
console.log(candidates);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句