Javascript json 数据分组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11248053/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript json data grouping
提问by ksumarine
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...
我有这样结构的 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"},
]}
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.
我将如何使用 Javascript/jQuery 完成此操作?不幸的是,我无法编辑服务器发送给我的内容。
回答by Ry-
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}));

