简体   繁体   English

排序嵌套对象的数组

[英]Sorting array of nested objects

I have the following data structure and I would like to sort them by "position". 我有以下数据结构,我想按“位置”对它们进行排序。

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

Here's what I tried so far, I can sort the outer object but I can't sort the components_under_section. 这是我到目前为止所尝试的,我可以对外部对象进行排序,但我无法对components_under_section进行排序。 Did I miss anything? 我错过了什么吗? Thanks in advance. 提前致谢。

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 ) );
})

Desired Output (sorting by components_under_section, then sort by outer object): 期望的输出(按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
      }
    ]
  }
]

You could take a callback for sorting by position and sort the outer array directly and then iterate and sort the inner arrays components_under_section . 您可以根据位置进行回调并直接对外部数组进行排序,然后对内部数组components_under_section进行迭代和排序。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM