简体   繁体   中英

How filter and sort in a nested tree Array in javascript?

I need to filter and sort a nested tree object for menu

so is sort and filter status === true,How to turn to

 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
  • One to sort items by their sort property

You can combine the two in any order you like.

itemFilter

The filter function takes a list of items. It goes over each of them and checks if it has children . If so, it filters those first. Then, it discards all items with status: false .

itemSorter

The sort function is very similar. 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)) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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