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

时间:2018-01-09 15:45:06

标签: javascript recursion

我有一个嵌套路线的对象。

任何路线 MAY 都包含路线childRoutes的列表。

我想获取包含密钥menu的所有路由的列表。



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');
&#13;
&#13;
&#13;

以上代码段尚未递归工作。

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

2 个答案:

答案 0 :(得分:3)

这个怎么样,似乎有用。

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/

答案 1 :(得分:2)

@ yBrodsky的答案可以用来隔离和展示通用的flatMap操作 - 在这里,您会看到路线被大部分reduce - map - {{ 1}}走出程序员的道路。

concat