2016-08-07 5 views
2

私はこの仕事をする年齢にしようとしていますが、私はかなり単純であると思っていましたが、タイプをグループ化して数えようと思っています。正しい形式のチェーンにこのjsonを取得する

私は日によって種類の発生をカウントし、この構造にそれを回すことができるようにする必要があり
[ 
    { 
    "type": "TypeOne", 
    "day": "2016-07-07" 
    }, 
    { 
    "type": "TypeOne", 
    "day": "2016-07-07" 
    }, 
    { 
    "type": "TypeTwo", 
    "day": "2016-07-07" 
    }, 
    { 
    "type": "TypeTwo", 
    "day": "2016-07-08" 
    }, 
    { 
    "type": "TypeTwo", 
    "day": "2016-07-08" 
    }, 
    { 
    "type": "TypeThree", 
    "day": "2016-07-08" 
    }, 
    { 
    "type": "TypeThree", 
    "day": "2016-07-09" 
    }, 
    { 
    "type": "TypeFour", 
    "day": "2016-07-09" 
    }, 
    { 
    "type": "TypeTwo", 
    "day": "2016-07-09" 
    }, 
    { 
    "type": "TypeThree", 
    "day": "2016-07-09" 
    }, 
    { 
    "type": "TypeThree", 
    "day": "2016-07-09" 
    }, 
    { 
    "type": "TypeFour", 
    "day": "2016-07-09" 
    } 
] 

[ 
    { 
    "date":"2016-07-07" 
    ,"TypeOne":2 
    ,"TypeTwo":1 
    ,"count":3 
    }, 
    { 
    "date":"2016-07-08" 
    ,"TypeTwo":2 
    ,"TypeThree":1 
    ,"count":3 
    }, 
    { 
    "date":"2016-07-09" 
    ,"TypeTwo":1 
    ,"TypeThree":3 
    ,"TypeFour":2 
    ,"count":6 
    } 
] 

私はそれが下線で動作するようにしようとしてきた、チェーン、GROUPBYとマップ、ちょうどそれが起こることができない。どんな方向にも感謝しています。

答えて

1

ジャスト構造を反復処理すると値が集計:はい、これが答えです

var dates = [ 
 
    { 
 
    "type": "TypeOne", 
 
    "day": "2016-07-07" 
 
    }, 
 
    { 
 
    "type": "TypeOne", 
 
    "day": "2016-07-07" 
 
    }, 
 
    { 
 
    "type": "TypeTwo", 
 
    "day": "2016-07-07" 
 
    }, 
 
    { 
 
    "type": "TypeTwo", 
 
    "day": "2016-07-08" 
 
    }, 
 
    { 
 
    "type": "TypeTwo", 
 
    "day": "2016-07-08" 
 
    }, 
 
    { 
 
    "type": "TypeThree", 
 
    "day": "2016-07-08" 
 
    }, 
 
    { 
 
    "type": "TypeThree", 
 
    "day": "2016-07-09" 
 
    }, 
 
    { 
 
    "type": "TypeFour", 
 
    "day": "2016-07-09" 
 
    }, 
 
    { 
 
    "type": "TypeTwo", 
 
    "day": "2016-07-09" 
 
    }, 
 
    { 
 
    "type": "TypeThree", 
 
    "day": "2016-07-09" 
 
    }, 
 
    { 
 
    "type": "TypeThree", 
 
    "day": "2016-07-09" 
 
    }, 
 
    { 
 
    "type": "TypeFour", 
 
    "day": "2016-07-09" 
 
    } 
 
]; 
 

 
var result = []; 
 

 
dates.forEach(function(d) { 
 
    var date = result.find(function(da) { return da.date === d.day; }); 
 
    if (!date) { 
 
    date = { date: d.day, count: 0 }; 
 
    result.push(date); 
 
    } 
 
    
 
    date.count++; 
 
    if(!date[d.type]) { 
 
    date[d.type] = 1; 
 
    } else { 
 
    date[d.type]++; 
 
    } 
 
}); 
 

 
console.log(result);

+0

を、本当にありがとうございましたTholle、これは私を殺しました!もう1つの質問ですが、「カウント」:合計フィールドをグループに追加して、各グループのすべてのアイテムの合計を表示できますか? – Nigel

+0

@Nigel確かに。質問と答えを編集しました。質問に答えた場合は、回答を受け入れることを検討してください。 – Tholle

関連する問題