我有一个对象数组:
results = session.query(Table1).filter(Table1.foo == 'x').all()
我希望能够以下列格式返回每年的聚合计数(非常类似于SQL中的一组):
[{person:101, year: 2012}, {person:102, year: 2012}, {person:103, year: 2013}]
在Vanilla Javascript中实现此目的的最佳方法是什么?
答案 0 :(得分:0)
您需要使用简单的内容,如下所示:
var data = [{person:101, year: 2011},
{person:102, year: 2012},
{person:103, year: 2011}];
var result = {},
i;
for(i=0; i < data.length; i++){
let year = data[i].year;
if(typeof result[year] === 'undefined'){
result[year] = 1;
}
else{
result[year] = result[year] + 1;
}
}
console.log(result);
答案 1 :(得分:0)
正如其他人所提到的,对象更适合聚合数据。您可以使用普通循环,或reduce来执行此操作:
var data = [{person:101, year: 2012}, {person:102, year: 2012}, {person:103,
year: 2013}];
var yearCounts = data.reduce(function (result, person) {
var currentCount = result[person.year] || 0;
result[person.year] = currentCount + 1;
return result;
}, {});
console.log(yearCounts);
如果你真的需要它作为数组,你可以循环对象并将其转换为数组:
var data = [{person:101, year: 2012}, {person:102, year: 2012}, {person:103,
year: 2013}];
var yearCounts = data.reduce(function (result, person) {
var currentCount = result[person.year] || 0;
result[person.year] = currentCount + 1;
return result;
}, {});
var year,
yearCountArray = [];
for (year in yearCounts) {
if (yearCounts.hasOwnProperty(year)) {
yearCountArray.push({
year: year,
count: yearCounts[year]
});
}
}
console.log(yearCountArray);
答案 2 :(得分:0)
使用按密钥归类的通用分组,它将计算每个分组中的项目数。我将从previous answer of mine中汲取灵感。该函数将返回另一个充当约简函数的函数,但是您始终可以将所需的键作为参数提供给它。
const groupByCounter = key => (result,current) => {
const item = Object.assign({},current);
if (typeof result[current[key]] == 'undefined'){
result[current[key]] = 1;
}else{
result[current[key]]++;
}
return result;
};
const data = [{person:101, year: 2012}, {person:102, year: 2012}, {person:103, year: 2013}];
const group = data.reduce(groupByCounter('year'),{});
console.log(group);