如何在javascript中编写递归平面地图?

我有一个嵌套路由的对象.

任何路由都可以包含路由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');

上面的代码段不能递归地工作.

如何在没有任何第三方库的情况下递归执行此操作?

最佳答案
怎么样,似乎工作.

const 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;
    },[])
}

https://jsfiddle.net/vv9odcxw/

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...