简体   繁体   English

如何在 javascript 中的嵌套树数组中进行过滤和排序?

[英]How filter and sort in a nested tree Array in javascript?

I need to filter and sort a nested tree object for menu我需要为菜单过滤和排序嵌套树 object

so is sort and filter status === true,How to turn to排序和过滤状态也是如此 === true,如何转向

 const items = [{ name: "a1", id: 1, sort: 1, status: true, children: [{ name: "a2", id: 2, sort: 1, status: true, children: [{ name: "a3", id: 3, sort: 2, status: true, }, { name: "a5", id: 4, sort: 1, status: true, } ] }] }, { name: "b2", id: 2, sort: 2, status: true, children: [{ name: "a2", sort: 1, status: false, id: 2, children: [{ name: "a3", id: 3, sort: 1, status: true, }] }, { name: "a4", id: 8, sort: 2, status: true, } ] } ]; console.log('items:', items)


const items = [{
    name: "a1",
    id: 1,
    sort: 1,
    status: true,
    children: [{
      name: "a2",
      id: 2,
      sort: 1,
      status: true,
      children: [{
          name: "a5",
          id: 4,
          sort: 1,
          status: true,
        },
        {
          name: "a3",
          id: 3,
          sort: 2,
          status: true,
        }
      ]
    }]
  },
  {
    name: "b2",
    id: 2,
    sort: 2,
    status: true,
    children: [{
      name: "a4",
      id: 8,
      sort: 2,
      status: true,
    }]
  }
];

I would write two recursive functions:我会写两个递归函数:

  • One to filter out the status: false items一、过滤掉status: false
  • One to sort items by their sort property一种按其sort属性对项目进行排序

You can combine the two in any order you like.您可以按照您喜欢的任何顺序将两者结合起来。

itemFilter

The filter function takes a list of items. filter function 获取项目列表。 It goes over each of them and checks if it has children .它遍历它们中的每一个并检查它是否有children If so, it filters those first.如果是这样,它首先过滤那些。 Then, it discards all items with status: false .然后,它丢弃所有status: false的项目。

itemSorter

The sort function is very similar. sort function 非常相似。 It goes over each item and checks if there are children.它检查每个项目并检查是否有孩子。 If so, it sorts those first.如果是这样,它首先对它们进行排序。 Then, it sorts the list it was passed.然后,它对传递的列表进行排序。

 const itemFilter = items => items.map(item => item.children? {...item, children: itemFilter(item.children) }: item ).filter(item => item.status); const itemSorter = items => items.map(item => item.children? {...item, children: itemSorter(item.children) }: item ).sort((i1, i2) => i1.sort - i2.sort); const items=[{name:"a1",id:1,sort:1,status:true,children:[{name:"a2",id:2,sort:1,status:true,children:[{name:"a3",id:3,sort:2,status:true},{name:"a5",id:4,sort:1,status:true}]}]},{name:"b2",id:2,sort:2,status:true,children:[{name:"a2",sort:1,status:false,id:2,children:[{name:"a3",id:3,sort:1,status:true}]},{name:"a4",id:8,sort:2,status:true}]}]; console.log( itemSorter(itemFilter(items)) );

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

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