【问题标题】:Sorting array of nested objects对嵌套对象数组进行排序
【发布时间】:2018-07-24 20:29:13
【问题描述】:

我有以下数据结构,我想按“位置”对它们进行排序。

[
  {
    "id": 52,
    "position": 2,
    "components_under_section": [
      {
       "id": 122,
       "position": 2
      },
      {
       "id": 123,
       "position": 1
      }
    ]
  },
  {
    "id": 53,
    "position": 1,
    "components_under_section": [
      {
       "id": 112,
       "position": 2
      },
      {
       "id": 113,
       "position": 1
      }
    ]
  }
]

到目前为止,这是我尝试过的,我可以对外部对象进行排序,但无法对 components_under_section 进行排序。我错过了什么吗?提前致谢。

array.sort( (a, b) => {
  let compAPosition = a[Object.keys(a)[0]]["position"];
  let compBPosition = b[Object.keys(b)[0]]["position"];

  if(a.components_under_section.length){
    a.components_under_section.sort ( (c, d) => {
      let compCPosition = c[Object.keys(c)[0]]["position"];
      let compDPosition = d[Object.keys(d)[0]]["position"];
      return ( compCPosition > compDPosition ? 1 : ((compDPosition > compCPosition ) ? -1 : 0 ) );
    })
  }

  return ( compAPosition > compBPosition ? 1 : ((compBPosition > compAPosition ) ? -1 : 0 ) );
})

期望的输出(按 components_under_section 排序,然后按外部对象排序):

[
  {
    "id": 53,
    "position": 1,
    "components_under_section": [
      {
       "id": 113,
       "position": 1
      },
      {
       "id": 112,
       "position": 2
      }
    ]
  },
  {
    "id": 52,
    "position": 2,
    "components_under_section": [
      {
       "id": 123,
       "position": 1
      },
      {
       "id": 122,
       "position": 2
      }
    ]
  }
]

【问题讨论】:

  • 你能发布你想要的输出吗?
  • a[Object.keys(a)[0]] 应该做什么?
  • @JonasW。我想它应该获取与a 的第一个属性相对应的值,尽管这是一个糟糕的主意。
  • @JonasW。是的,这是一个 id
  • 数字通常没有“位置”属性...

标签: javascript


【解决方案1】:

您可以通过回调进行按位置排序并直接对外部数组进行排序,然后对内部数组进行迭代和排序components_under_section

const sortByPosition = (a, b) => a.position - b.position
array.sort(sortByPosition);
array.forEach(({ components_under_section }) => components_under_section.sort(sortByPosition));

【讨论】: