2015-02-06 88 views
0

[更新]:由于JSON数据格式已更改,因此我已删除大部分布局和lodash(失败代码)。lodash通过多个键分组数组

我试图将数据集分组以准备汇总总计。这是传入的JSON布局。我需要组由国家,然后通过品牌:

[ 
    { 
     $id: "1", 
     countryCode: "HT", 
     brand: "CO", 
     roomNights: 12, 
     hotelSpend: 2000 
    }, 
    { 
    $id: "2", 
    countryCode: "PK", 
    brand: "HH", 
    roomNights: 201, 
    hotelSpend: 10000 
    }, 
    { 
    $id: "3", 
    countryCode: "RO", 
    brand: "CO", 
    roomNights: 34, 
    hotelSpend: 5000 
    }, 
    { 
    $id: "4", 
    countryCode: "US", 
    brand: "ES", 
    roomNights: 120, 
    hotelSpend: 56000 
    }, 
    { 
    $id: "5", 
    countryCode: "PK", 
    brand: "HH", 
    roomNights: 145, 
    hotelSpend: 33000 
    } 
    ] 

的数据需要被转化成这种格式:

 ['Brand','HT'  , 'PK'  , 'US'  , 'RO', 'Avg Rm', 'Avg Spend'] 
     ['HH' ,'0/0' ,'201/10000', '0/0'  , '0/0'  , 201, 10000], 
     ['CO' ,'12/2000','0/0',  , '0/0'  , '34/5000', 23 , 3500], 
     ['ES' , '0/0' ,'0/0' , '120/50000' , '0/0' , 120, 50000] 

的roomNights和hotelSpend将每个品牌&全国范围内总计和平均每个都需要在最后计算字段。

谢谢!

+0

我想帮忙,但我无法确切地告诉你在找什么。你能发表一个你希望得到的输出的例子吗? – 2015-02-14 07:57:07

+0

我可以在纯js中做到这一点,但我想这不是你要找的 – taesu 2015-02-16 05:39:56

+0

我对它开放。无论更轻:-) @taesu – 2015-02-16 17:53:30

回答

2

让我们先定义一个mean功能,并把它添加到_

_.mixin({ 
    mean: function(ds) { 
    return _(ds).foldr(function(a, b) { return a + b; }, 0)/ds.length; 
    } 
}); 

让我们来定义功能选择的行和列:

var row = function(d) { return d.brand; }; 
var col = function(d) { return d.countryCode; }; 

aggr函数接受我们的数据的子列表并将其值汇总为一个值(这里是有理数的字符串表示):

var aggr = function(ds) { 
    var val = _(ds).foldr(function(a, b) { 
    return { 
     roomNights: a.roomNights + b.roomNights, 
     hotelSpend: a.hotelSpend + b.hotelSpend 
    }; 
    }, {roomNights: 0, hotelSpend: 0}); 

    return val.roomNights + "/" + val.hotelSpend; 
}; 

我们的行和列的标签:

rows = _.chain(data).map(row).unique().value(); 
columns = _.chain(data).map(col).unique().value(); 

枢轴:

[["Brand/Country"].concat(columns).concat(["Avg Rm", "Avg Spend"])] // header row 
.concat(_(rows).map(function(r){ 

    // data in this row 
    rdata = _(data).filter(function(d) { return row(d) == r; }); 

    return [r].concat(_(columns).map(function(c){ 
    return aggr(_(rdata).filter(function(d) {return col(d) == c; })); 
    })) 
    // the last two columns in each row 
    .concat([ 
    _.chain(rdata).map(function(d) { return d.roomNights; }).mean().value(), 
    _.chain(rdata).map(function(d) { return d.hotelSpend; }).mean().value() 
    ]); 
})); 

可以通过修改rowscolumns阵列,类似的控制顺序或过滤由特定countryCodebrand结果到电子表格。

+0

谢谢@homam! – 2015-02-24 04:10:01