You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中实现递归Flat Map提取嵌套路由中含menu的路由?

递归提取嵌套路由中含menu键的路由列表

我来帮你解决这个嵌套路由提取的问题~你之前用的deepFlatten函数只能处理纯数组的层级嵌套,但你的路由是对象包含childRoutes子数组的嵌套结构,所以得针对性写递归逻辑。

实现思路

我们需要写一个递归函数,核心做两件事:

  1. 检查当前路由是否带有menu属性,有的话就加入结果列表
  2. 如果当前路由存在childRoutes子路由数组,就递归处理这个子数组,把结果合并到总列表里

具体代码实现

const extractMenuRoutes = (routes) => {
  let result = [];
  routes.forEach(route => {
    // 若当前路由有menu,直接加入结果
    if (route.menu) {
      result.push(route);
    }
    // 存在子路由数组时,递归处理并合并结果
    if (route.childRoutes && Array.isArray(route.childRoutes)) {
      result = result.concat(extractMenuRoutes(route.childRoutes));
    }
  });
  return result;
};

// 你的测试路由结构
const routes = [{ 
  "name": "userManagement", 
  "childRoutes": [ 
    { 
      "name": "blogManagement", 
      "childRoutes": [ 
        { 
          "name": "blog", 
          "menu": { "role": 1020 } 
        } 
      ], 
    }, 
    { 
      "name": "organizationList", 
      "menu": { "role": 1004 } 
    } 
  ], 
}, { 
  "name": "test", 
  "menu": { "role": 4667 } 
}];

// 验证结果
const links = extractMenuRoutes(routes);
console.log('it should have a length of 3:', links.length === 3); // true
console.log('it should be blog:', links[0].name === 'blog'); // true
console.log('it should be organizationList:', links[1].name === 'organizationList'); // true
console.log('it should be test:', links[2].name === 'test'); // true

代码说明

  • 函数extractMenuRoutes接收路由数组作为参数,初始化空结果数组
  • 遍历每个路由对象:
    • 优先判断是否存在menu属性,存在则将当前路由对象加入结果
    • 再检查是否有childRoutes且为数组,若是则递归调用自身处理子路由,将子结果合并到总结果中
  • 最终返回所有符合条件的路由列表

这样就能完美适配你的嵌套路由结构,精准提取所有带menu的路由啦~

内容的提问来源于stack exchange,提问作者Dimitri Kopriwa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:17:44