JavaScript中按属性对整个嵌套对象进行排序

3

我希望能够遍历一个深度嵌套的对象,并按属性排序每个层级。在这种情况下是按 id 排序。

这是我的对象(实际上会有更多层级,这里为了易读性只添加了3个层级):

const myObj = [
  {
    id: 15,
    children: [
      {
        id: 9,
        children: [
          {
            id: 4,
            children: []
          },
          {
            id: 1,
            children: []
          }
        ]
      },
      {
        id: 4,
        children: [
          {
            id: 35,
            children: [
              {
                id: 12,
                children: []
              },
              {
                id: 8,
                children: []
              }
            ]
          },
          {
            id: 30,
            children: [],
          }
        ]
      },
    ]
  },
  {
    id: 2,
    children: [
      {
        id: 9,
        children: []
      },
      {
        id: 3,
        children: []
      },
    ]
  }
]

以下是期望的输出:

const myObj = [
  {
    id: 2,
    children: [
      {
        id: 3,
        children: []
      },
      {
        id: 9,
        children: []
      }
    ]
  },
  {
    id: 15,
    children: [
      {
        id: 4,
        children: [
          {
            id: 30,
            children: [],
          },
          {
            id: 35,
            children: [
              {
                id: 8,
                children: []
              },
              {
                id: 12,
                children: []
              }
            ]
          },
        ]
      },
      {
        id: 9,
        children: [
          {
            id: 1,
            children: []
          },
          {
            id: 4,
            children: []
          }
        ]
      },
    ]
  }
]

以下是我尝试对其进行排序的结果:

const myObj = [{id:15,children:[{id:9,children:[{id:4,children:[]},{id:1,children:[]}]},{id:4,children:[{id:35,children:[{id:12,children:[]},{id:8,children:[]}]},{id:30,children:[],}]},]},{id:2,children:[{id:9,children:[]},{id:3,children:[]},]}]

function sortByOrderIndex(obj) {
  obj.sort((a, b) => (a.orderindex > b.orderindex) ? 1 : ((b.orderindex > a.orderindex) ? -1 : 0));

  return obj;
}

function sortNestedObj(obj) {
  sortByOrderIndex(obj);

  for (let i = 0; i < obj.length; i++) {
    const t = obj[i];

    if (t.children.length !== 0) {
      sortNestedObj(t.children);
    } else {
      return;
    }
  }
}

console.log(sortByOrderIndex(myObj))

我创建了一个函数来排序一个对象,然后尝试创建另一个对象,遍历每个具有子级的对象,并使用第一个函数对这些子级进行排序。如果这些子级有子级,则继续排序,直到某个子级没有子级为止。
4个回答

4
你可以像这样递归地排序数组和它的对象的子元素:

const myObj = [{id:15,children:[{id:9,children:[{id:4,children:[]},{id:1,children:[]}]},{id:4,children:[{id:35,children:[{id:12,children:[]},{id:8,children:[]}]},{id:30,children:[],}]},]},{id:2,children:[{id:9,children:[]},{id:3,children:[]},]}]

function sortArray(array) {
  array.sort((a, b) => a.id - b.id);
  array.forEach(a => {
    if (a.children && a.children.length > 0)
      sortArray(a.children)
  })
  return array;
}

console.log(sortArray(myObj))


1
你可以编写一个递归排序函数:

const myObj = [{id:15,children:[{id:9,children:[{id:4,children:[]},{id:1,children:[]}]},{id:4,children:[{id:35,children:[{id:12,children:[]},{id:8,children:[]}]},{id:30,children:[],}]},]},{id:2,children:[{id:9,children:[]},{id:3,children:[]},]}]

const orderChildren = obj => {
  obj.children.sort((a, b) => a.id - b.id);
  if (obj.children.some(o => o.children.length)) {
    obj.children.forEach(child => orderChildren(child));
  }
  return obj;
};

const myNewObj = myObj.map(o => orderChildren(o)).sort((a, b) => a.id - b.id);

console.log(myNewObj);
.as-console-wrapper { max-height: 100% !important; top: 0; }


1

你可以做:

const myObj = [{id: 15,children: [{id: 9,children: [{id: 4,children: []},{id: 1,children: []}]},{id: 4,children: [{id: 35,children: [{id: 12,children: []},{id: 8,children: []}]},{id: 30,children: [],}]},]},{id: 2,children: [{id: 9,children: []},{id: 3,children: []},]}];
const deepSortById = arr => (arr.forEach(a => a.children && deepSortById(a.children)), arr.sort((a, b) => a.id - b.id));

const result = deepSortById(myObj);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }


0
我创建了一个通用的解决方案,用于按id对嵌套数组进行排序。我的解决方案适用于任何嵌套数组,并根据id属性进行排序。或者根据您在方法的第二个参数中指定的任何其他属性进行排序。
function sortNestedArrays(obj, sortPropertyName) {
    Object.keys(obj).forEach((key) => {
        if (Array.isArray(obj[key])) {
            obj[key].sort((a, b) => a[sortPropertyName] - b[sortPropertyName]);
        }

        if (!!obj[key] && (typeof obj[key] === 'object' || Array.isArray(obj[key]))) {
            sortNestedArrays(obj[key], sortPropertyName);
        }
    });

    return obj;
}

使用方法如下:

obj = sortNestedArrays(obj, 'id');

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接