web-dev-qa-db-ja.com

Javascriptjsonデータのグループ化

これが以前に尋ねられた場合は申し訳ありませんが、私が達成しようとしていることの良い例を見つけることができませんでした。たぶん私は正しいものを探していません。どこかに説明があれば訂正してください。とにかく...

私はJSONデータをそのように構造化しています...

{"Result":[
    {"Level":"ML","TeamName":"Team 1","League":"League 1"},
    {"Level":"ML","TeamName":"Team 2","League":"League 2"},
    {"Level":"ML","TeamName":"Team 3","League":"League 3"},
    {"Level":"3A","TeamName":"Team 4","League":"League 1"},
    {"Level":"3A","TeamName":"Team 5","League":"League 2"},
    {"Level":"3A","TeamName":"Team 6","League":"League 3"},
    {"Level":"2A","TeamName":"Team 7","League":"League 1"},
    {"Level":"2A","TeamName":"Team 8","League":"League 2"},
    {"Level":"2A","TeamName":"Team 9","League":"League 3"},
]}

グループ化するか、そのように再構築したい...

{"Result":[
    {"ML":[
        {"TeamName":"Team 1","League":"League 1"},
        {"TeamName":"Team 2","League":"League 2"},
        {"TeamName":"Team 3","League":"League 3"}
    ]},
    {"3A":[
        {"TeamName":"Team 4","League":"League 1"},
        {"TeamName":"Team 5","League":"League 2"},
        {"TeamName":"Team 6","League":"League 3"}
    ]},
    {"2A":[
        {"TeamName":"Team 7","League":"League 1"},
        {"TeamName":"Team 8","League":"League 2"},
        {"TeamName":"Team 9","League":"League 3"}
    ]}
]}

Javascript/jQueryでこれをどのように達成しますか?残念ながら、サーバーから送信されたものを編集できません。

18
ksumarine

オブジェクト内ですべてを追跡するだけです。

let groups = Object.create(null);

data.forEach(item => {
    if (!groups[item.Level]) {
        groups[item.Level] = [];
    }

    groups[item.Level].Push({
        TeamName: item.TeamName,
        League: item.League
    });
});

let result =
    Object.entries(groups)
        .map(([k, v]) => ({[k]: v}));
26
Ry-