js用递归的方式过滤数组

最近遇到一个问题,先贴代码
[
{path:'levelone',name:'第一级',iconClass:'fa-navicon',isRoot:true,subMenus:[
{path:'leveltwo',name:'第二级',iconClass:'fa-navicon',subMenus:[
{path:'levelthree',name:'第三级',roles:['admin'],iconClass:'fa-navicon'}
]},
{path:'leveltwo_R',name:'第二级_R',iconClass:'fa-navicon'}
]},
{path:'user',name:'用户管理',roles:['admin'],iconClass:'fa-language',isRoot:true},
{path:'dictionary',name:'字典管理',roles:['admin'],iconClass:'fa-language',isRoot:true},
{path:'role',name:'角色管理',roles:['admin'],iconClass:'fa-vcard',isRoot:true},
{path:'outline',name:'违规管理',roles:['admin'],iconClass:'fa-exclamation-triangle',isRoot:true}
]
我有这样的一个数组,且数组层级未知,其叶子节点上都roles属性,如果没有或不包含admin,则需要筛选掉。请问怎么解决?这里肯定是需要用递归来实现的,我用了filter,但是在有subMenus的节点上,我用的是some来过滤
filterRoutes(route,role){
if(route.subMenus&&route.subMenus.length){
returnroute.subMenus.some((item)=>{
returnthis.filterRoutes(item,role);
});
}else{
returnroute.roles&&-1}
}
导致leveltwo_R这个节点没有被遍历,就是这里没有想明白,求指点
吃鸡游戏
浏览 1712回答 2
2回答

撒科打诨

varf=item=>{if(item['subMenus']){item['subMenus']=item['subMenus'].filter(f);returntrue;}elseif(item['roles']){returnitem['roles'].indexOf('admin')!==-1;}else{returnfalse;}}varresult=data.filter(f);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript