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.
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}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With