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, }] } ];
Advertisement
Answer
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)) );