Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
29
rated 0 times [  35] [ 6]  / answers: 1 / hits: 21734  / 12 Years ago, thu, june 28, 2012, 12:00:00

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.


More From » jquery

 Answers
40

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

[#84592] Wednesday, June 27, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sam

Total Points: 711
Total Questions: 96
Total Answers: 107

Location: Burkina Faso
Member since Thu, Dec 23, 2021
2 Years ago
;