使用Array.prototype.reduce函数的简单解决方案:
// Replace arr with your actual array!
var arr = [
{ AGENDADOR: 'AGE270', TOTAL : 6},
{ AGENDADOR: 'AGE270', TOTAL : 3},
{ AGENDADOR: 'AGE203', TOTAL : 5},
{ AGENDADOR: 'AGE028', TOTAL : 9},
],
totals = arr.reduce(function (r, o) {
(r[o.AGENDADOR])? r[o.AGENDADOR] += o.TOTAL : r[o.AGENDADOR] = o.TOTAL;
return r;
}, {});
console.log(totals);
arr.reduce(callback, [initialValue])
initialValue
Optional. Value to use as the first argument to the first call of the callback.
var data; // the data represented by your screenshot
var counts = _.chain(data)
.groupBy('AGENDADOR')
.map(_.size)
.value();
counts
现在将会是这样一个对象:
{
"AGE270": 9,
"AGE203": 5,
// etc
}
var sum = {};
yourArray.forEach(function(item) {
if(sum[item.AGENDADOR] === undefined) {
sum[item.AGENDADOR] = 0;
}
sum[item.AGENDADOR] += item.TOTAL
});
sum
对象中每个键对应的总数。类似于这样:{
AGE270: 9,
AGE203: 5,
AGE208: 9
}
试一下这个:
function( data ){
var outputObj = {} ;
for(var i=0;i < data.length; i++){
datum = data[i];
if(outputObj[datum.AGENDADOR])
outputObj[datum.AGENDADOR] += parseInt( datum.TOTAL) ;
else
outputObj[datum.AGENDADOR] = parseInt( datum.TOTAL);
}
return outputObj;
};
怎么样使用一个简单的map()函数?就像这样:
var t = YourArray;
var u = t.map(function (a, i) { var g = {}; g[a.AGENDADOR] = a.TOTAL; return g; });