Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript json data grouping [closed]

Sorry if this has been asked before, but I couldn't find a good example of what I'm trying to accomplish. Maybe I'm just not searching for the right thing. Please correct me if there's an explanation of this somewhere. Anyway...

I have JSON data structured like so...

{"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"},
]}

I would like to group, or restructure it like so...

{"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"}
    ]}
]}

How would I accomplish this with Javascript/jQuery? Unfortunately I can't edit what the server is sending me.

like image 495
ksumarine Avatar asked Jun 28 '12 15:06

ksumarine


1 Answers

Just keep track of it all in an object:

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}));
like image 116
Ry- Avatar answered Nov 09 '22 07:11

Ry-