我有一个嵌套路由的对象.
任何路由都可以包含路由childRoutes的列表.
我想获得包含关键菜单的所有路线的列表.
const routes = [{
"name": "userManagement","childRoutes": [
{
"name": "blogManagement","childRoutes": [
{
"name": "blog",// <=== I want to have this route
"menu": {
"role": 1020
}
}
],},{
"name": "organizationList",// <=== and this one
"menu": {
"role": 1004
}
}
],{
"name": "test","menu": { "role": 4667 }
}];
const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v)));
// Should handle nesting of route
const links = deepFlatten(routes).filter((r) => !!r.menu);
console.log('it should have a length of 3:',links.length === 3);
console.log('it should be blog:',links[0].name === 'blog');
console.log('it should be organizationList:',links[1].name === 'organizationList');
console.log('it should be test:',links[2].name === 'test');
上面的代码段不能递归地工作.
如何在没有任何第三方库的情况下递归执行此操作?
最佳答案
怎么样,似乎工作.
原文链接:https://www.f2er.com/js/429240.htmlconst flatten = (routes) => {
return routes.reduce((acc,r) => {
if(r.childRoutes && r.childRoutes.length) {
acc = acc.concat(flatten(r.childRoutes));
} else {
acc.push(r);
}
return acc;
},[])
}