按键分组对象并返回新对象

问题描述 投票:0回答:0

我有一组对象,我需要以适合我的方式在 JavaScript 中对其进行排序。

这是我拥有的数组示例:

[
  {
    "id": "AD012014001R",
    "country": "AD",
    "series": 1,
    "issue_year": 2014
  },
  {
    "id": "AD012014002R",
    "country": "AD",
    "series": 1,
    "issue_year": 2014
  },
  {
    "id": "AT012002002R",
    "country": "AT",
    "series": 1,
    "issue_year": 2002
  },
  {
    "id": "BE011999100R",
    "country": "BE",
    "series": 1,
    "issue_year": 1999
  },
  {
    "id": "BE011999200R",
    "country": "BE",
    "series": 1,
    "issue_year": 1999
  },
  {
    "id": "BE022008001R",
    "country": "BE",
    "series": 2,
    "issue_year": 2008
  }
]

我的输出应该是这样的:

[
  {
    "country": "AD",
    "series": [
      {
        "series": 1,
        "coins": [
          {
            "id": "AD012014001R",
            "country": "AD",
            "series": 1,
            "issue_year": 2014
          },
          {
            "id": "AD012014002R",
            "country": "AD",
            "series": 1,
            "issue_year": 2014
          }
        ]
      }
    ]
  },
  {
    "country": "AT",
    "series": [
      {
        "series": 1,
        "coins": [
          {
            "id": "AT012002002R",
            "country": "AT",
            "series": 1,
            "issue_year": 2002
          }
        ]
      }
    ]
  },
  {
    "country": "BE",
    "series": [
      {
        "series": 1,
        "coins": [
          {
            "id": "BE011999100R",
            "country": "BE",
            "series": 1,
            "issue_year": 1999
          },
          {
            "id": "BE011999200R",
            "country": "BE",
            "series": 1,
            "issue_year": 1999
          }
        ]
      },
      {
        "series": 2,
        "coins": [
          {
            "id": "BE022008001R",
            "country": "BE",
            "series": 2,
            "issue_year": 2008
          }
        ]
      }
    ]
  }
]

所以我的 API 响应必须更大,但这只是其中的一小部分。我得到了数百个看起来像这样的对象的数组,需要对它们进行排序并返回它们,首先按国家排序,然后按每个国家下的系列排序。我知道有很多类似的问题,但我想不通,因为我的问题比所有问题都复杂一点。

javascript json sorting object multidimensional-array
© www.soinside.com 2019 - 2024. All rights reserved.