首页 > 解决方案 > 将数组排序到新的二维数组

问题描述


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

标签: javascriptarraystypescript

解决方案


您需要遍历它并根据您的联赛 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);
});

推荐阅读