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

前端之家收集整理的这篇文章主要介绍了如何在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/

原文链接:https://www.f2er.com/js/429240.html

猜你在找的JavaScript相关文章