javascript - 将数组排序到新的二维数组
问题描述
[
{
"id": 3401,
"league": {
"id": 4140,
"image_url": "pngurl.png",
"modified_at": "2019-02-19T15:29:07Z",
"name": "League Cup",
"slug": "league-slug",
"url": null
}
}
]
我在数组中有很多这样的对象。如何对数组进行排序/格式化,这样我得到了一个新数组/字典,其中的对象按"id"
in的值排序,"league"
例如 it's 4140
。现在我有一个普通数组,但我想要一些按键值排序的东西,比如 4140: [objects from array with League id 4140] 或 2d array sorted [[array with all objects containing league with value "id" of 4140], [array with objects with league value id 4141], etc..]
。我需要使用map
或类似的东西吗?我对 Javascript 很陌生。
这是我期望在代码中得到的。
//THIS is what I want to get in the end...
[
{
"league": "League Cup",
"tournaments": [
{
"id": 3402,
"league": {
"id": 4141,
"image_url": "pngurl.png",
"modified_at": "2019-02-19T15:29:07Z",
"name": "League Cup",
"slug": "league-slug",
"url": null
}
},
{
"id": 3403,
"league": {
"id": 4141,
"image_url": "pngurl.png",
"modified_at": "2019-02-19T15:29:07Z",
"name": "League Cup",
"slug": "league-slug",
"url": null
}
}
]
},
{
"league": "League Cup 2",
"tournaments": [
{
"id": 3401,
"league": {
"id": 4145,
"image_url": "pngurl.png",
"modified_at": "2019-02-19T15:29:07Z",
"name": "League Cup 2",
"slug": "league-slug",
"url": null
}
},
{
"id": 3405,
"league": {
"id": 4145,
"image_url": "pngurl.png",
"modified_at": "2019-02-19T15:29:07Z",
"name": "League Cup 2",
"slug": "league-slug",
"url": null
}
}
]
}
]
解决方案
您需要遍历它并根据您的联赛 ID 将它们分组到一个新对象中。
例子:
const output = {};
const input = [
{
"id": 1,
"league": {
"id": 7,
"image_url": "pngurl.png",
"modified_at": "2019-02-19T15:29:07Z",
"name": "League Cup",
"slug": "league-slug",
"url": null
}
},
{
"id": 2,
"league": {
"id": 7,
"image_url": "pngurl.png",
"modified_at": "2019-02-19T15:29:07Z",
"name": "League Cup",
"slug": "league-slug",
"url": null
}
},
{
"id": 3,
"league": {
"id": 8,
"image_url": "pngurl.png",
"modified_at": "2019-02-19T15:29:07Z",
"name": "League Cup",
"slug": "league-slug",
"url": null
}
}
];
input.forEach(x => {
if (!output[x.league.id]) {
output[x.league.id] = [];
}
output[x.league.id].push(x);
});
推荐阅读
- shader - 错误:GL_INVALID_OPERATION:glUniform1iv:非数组Phaser 3.52的计数> 1
- javascript - innerHTML 属性不适用于 owl carousel
- microstack - Microstack libvirt如何开启TCP监听模式
- php - How to solve ERR_INVALID_REDIRECT for an HTTPS Wordpress website on Apache behind Nginx and varnish?
- python - 无法分割手写字符
- sql - 目标主体名称不正确。无法生成 SSPI 上下文(cmd 提示符中的 SPN 显示现有)
- tensorflow - Keras 保存模型后加载模型,为什么要从头开始训练?
- javascript - 获取除自身以外的页面的html页面标题
- r - 使用并行处理的函数进行并行处理?
- c++ - 增强几何返回相交和相交的不一致结果