具有相似键值的Sum对象

时间:2015-03-11 19:41:24

标签: javascript node.js

我有一组像这样的对象:

var objects = [{a:'b',c:'d',count:1},{a:'b',c:'d',count:2},{a:'y',c:'d',count:4}]

我想将具有相同ab值的所有计数相加,以制作类似的内容:

{a:'b',c:'d',count:3},{a:'y',c:'d',count:4}

有一种简单的方法吗?

4 个答案:

答案 0 :(得分:0)

对于这种情况,您可以轻松地按a + b:

的值对对象进行分组
var objects = [{a:'b',c:'d',count:1},{a:'b',c:'d',count:2},{a:'y',c:'d',count:4}]


function getId(obj){ // how to group the objects
    return obj.a + '|'+ obj.c
}


var groups = {};

for(var i=0;i<objects.length;i++){ // for each obj
    var id = getId(objects[i])  // get id
    if(groups.hasOwnProperty(id)){ // if group is already created, add count
        groups[id].count += objects[i].count         
    }else{ // else create group with same values
        groups[id] = {a:objects[i].a, c: objects[i].c, count:objects[i].count}
    }
}

console.log(groups) // you can then change the groups to an array if you want

答案 1 :(得分:0)

有一个很棒的名为ramda的库,它非常适合编写复杂的数据操作:

var R = require('ramda'); // Edit: you can also use a script tag if you're working in the browser. see http://ramdajs.com/

// Concatenate the values for a & c so that we group by values
var groups = R.groupBy(R.converge(R.concat, R.prop('a'), R.prop('c')), objects);

// We just want the grouped arrays, not the concatenated keys
groups = R.values(groups);

var aggregateCounts = R.compose(R.sum, R.pluck('count'));

groups = groups.map(function(group) {
  return {
    a: group[0].a,
    c: group[0].c,
    count: aggregateCounts(group)
  };
});

答案 2 :(得分:0)

您可以对objects数组进行排序,然后通过将对象推送到ac更改来创建新数组:

var objects = [{a:'b',c:'d',count:1},{a:'y',c:'d',count:4},{a:'b',c:'d',count:2}],
    newobj = [];
    
objects.sort(function(a,b) {
  return a.a+a.c > b.a+b.c ?  1 :
         a.a+a.c < b.a+b.c ? -1 :
         0;
});

for(var i = 0 ; i < objects.length ; i++) {
  if(i === 0 || objects[i].a !== objects[i-1].a || objects[i].b !== objects[i-1].b) {
    newobj.push({a: objects[i].a, c: objects[i].c, count: objects[i].count});
  }
  else {
    newobj[newobj.length-1].count+= objects[i].count;
  }
}

alert(JSON.stringify(newobj));

答案 3 :(得分:0)

只需按键分组:

var aggregate = function (objects) {
    var map = {}; // map to store data
    var a = [];   // temporary array to hold the objects
    objects.forEach(function (d) {
        var key = d.a > d.c ? String(d.c) + d.a : String(d.a) + d.c;
        // if {a:2,c:3} is the same as {c:2,a:3}, use the above,
        // otherwise, just use key = String(d.a) + String(d.c);
        map[key] = (map[key] || 0) + d.count;
    })
    // e.g., key === "bd"
    for (var key in map) {
        // so split it into ["b", "d"]
        var k = key.toString().split("");
        // and push it to the temp array as the appropriate object
        a.push({ a: k[0], c: k[1], count: map[key] });
    }
    return a;
}

var objects = [{a:'b',c:'d',count:1},{a:'b',c:'d',count:2},{a:'y',c:'d',count:4}];
console.log(aggregate(objects));
// [{a:"b",c:"d",count:3},{a:"d",c:"y",count:4}]
相关问题