2015-02-06 1 views
0

[업데이트] : JSON 데이터 형식이 변경 되었기 때문에 레이아웃과 대다수 (실패한 코드)를 이전에 제거했습니다.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

저는 도와 드리고 싶지만, 당신이 찾고있는 것을 정말로 말할 수는 없습니다. 얻을 수있는 결과물의 예를 게시 할 수 있습니까? –

+0

나는 이걸 순수 js에서 할 수는 있지만, 그게 당신이 찾고있는 것이 아닌 것 같아 – taesu

+0

나는 그것에 대해 개방적이다. 더 가벼운 것은 무엇이든 :-) @taesu –

답변

2

하자 먼저 mean 함수를 정의하고 _에 추가

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

aggr 기능은 우리의 데이타의 서브리스트를 취

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

이야는 행 및 열을 선택하기위한 기능을 정의 할 그 값을 하나의 값 (합리적인 수의 문자열 표현)으로 집계합니다.

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(); 

피벗 : 당신은, 유사한 rowscolumns 배열을 수정하여 특정 countryCode 또는 brand에 의한 결과를 순서를 제어하거나 필터링 할 수 있습니다

[["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() 
    ]); 
})); 

스프레드 시트로

+0

@homam! –