使用Underscore.js“groupBy”函数后显示数组的内容

时间:2014-07-28 00:37:28

标签: jquery underscore.js

我有一组数据要按月分组:

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'
        }
    }
]

我认为,这应该允许我有一个内循环来计算重量,并按最初按月分组时按重量进行分组。

1 个答案:

答案 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 

Live Demo