19

抱歉,如果以前有人问过这个问题,但我找不到一个很好的例子来说明我正在努力完成的事情。也许我只是没有在寻找正确的东西。如果某处对此有解释,请纠正我。反正...

我有这样的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 完成此任务?不幸的是,我无法编辑服务器发送给我的内容。

4

1 回答 1

28

只需在一个对象中跟踪它:

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}));
于 2012-06-28T15:42:03.880 回答