我有一组数据要按月分组:
var data = [
{WT: 'Brick', Month: 'January', Weight: '50'},
{WT: 'Brick', Month: 'January', Weight: '55'},
{WT: 'Metal', Month: 'January', Weight: '150'},
{WT: 'Paper', Month: 'March', Weight: '10'},
{WT: 'Paper', Month: 'March', Weight: '12'},
]
到目前为止,我有这个代码按月分组:
var groupedCo2 = _.groupBy(data, 'Month');
但是,我现在需要将所有Weight
值一起添加,并按WT
值将它们组合在一起。当我为console.log
var执行groupedCo2
时,我会看到其中包含的月份和剩余数据,但每次我尝试显示包含的信息时,我都会收到object
错误消息或undefined
。
如果使用underscore.js,我可以在数据最初分组后访问变量吗?
修改
我正在寻找的数据结构是伪方式:
var data = [
{
Month: 'January'
{
WT: 'Brick',
Weight: '50'
}
}
]
我认为,这应该允许我有一个内循环来计算重量,并按最初按月分组时按重量进行分组。
答案 0 :(得分:2)
听起来你正在寻找按月分组的重量总和,然后是WT?如果是这样,它会看起来像这样......
var groupedData = _.chain(data)
.groupBy('Month')
.map(function (group, key) {
return {
Month: key,
WTs: _.chain(group)
.groupBy("WT")
.map(function (group, key) {
return {
WT: key,
TotalWeight: _.reduce(group, function(memo, i){
return memo + parseInt(i.Weight, 10);
}, 0)
};
})
.value()
}})
.value();
结果是:
[
{
"Month": "January",
"WTs": [
{
"WT": "Brick",
"TotalWeight": 105
},
{
"WT": "Metal",
"TotalWeight": 150
}
]
},
{
"Month": "March",
"WTs": [
{
"WT": "Paper",
"TotalWeight": 22
}
]
}
]
你可以像这样循环:
_.each(groupedData, function(m) {
console.log("Month: ", m.Month);
_.each(m.WTs, function(wt) {
console.log(" ", wt.WT, ": ", wt.TotalWeight);
});
});
哪个输出:
Month: January
Brick : 105
Metal : 150
Month: March
Paper : 22