迭代通过对象添加所有匹配的属性

时间:2014-03-21 02:47:51

标签: javascript jquery arrays object comparison

我有一个caml查询,它将在xml中返回类似的内容。

    ID      Title        Percentage
    7;#7    2       1.00000000000000
    7;#7    3       0.220000000000000
    7;#7    sub 1.1     0
    7;#7    4       0.140000000000000
    12;#12  7       0.670000000000000
    13;#13  6       0.700000000000000

我可能会为每个项目创建一个对象的aray。像这样:

var result = [{id:7,title:"2",percent:1.0},...,{id:13,title:"6",percent:0.7}]

我怎样才能遍历result并将所有百分比加起来使用相同的ID,这样我最终得到的结果如下:

var total = [{id:7,percent:1.36,count:4},{id:12,percent:0.67,count:1},{id:13,percent:0.7,count:1}] 

或者即使我能得到 percent/count = totalPercentage所以我最终得到的对象只有{id:7,totalPercentage:0.325}

2 个答案:

答案 0 :(得分:1)

试试这个:

var percentages = {};

result.forEach(function (it) {
  var obj = percentages[it.id] = percentages[it.id] || {
    percent: 0, 
    count: 0, 
    id: it.id
  };
  obj.percent += Number(it.percent); // Casting to Number, in case percent comes as string
  obj.count++;
});

这会创建一个对象,其中id为键。您是否希望将其转换为数组:

total = Object.keys(percentages).map(function (it) {
  return percentages[it]
});

要获得百分比的平均值,您可以这样做:

total = total.map(function(it) {
  return {
    id: it.id, 
    percent: it.percent / it.count
  };
});

答案 1 :(得分:0)

只需创建新对象并遍历旧对象即可。您可以在此处查看演示:http://jsfiddle.net/TSyE5/2/

var totalPercent = [],
    total = {},
    result = [{id:8,title:"3",percent:1.0},{id:7,title:"2",percent:1.0},{id:7,title:"2",percent:3.0},{id:13,title:"6",percent:0.7},{id:13,title:"6",percent:0.7},{id:13,title:"6",percent:0.7}];
$.each(result, function(){
    !(this.id in total) && (total[this.id] = {id:this.id, title:this.title, percent:0, count:0});
    total[this.id].percent += this.percent;
    total[this.id].count++;
});

$.each(total, function(i){
    total[i].percent = total[i].percent/total[i].count;
    totalPercent.push({id:total[i].id, percent:total[i].percent});
});