微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在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.jb51.cc/js/429240.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐