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

如何根据visible属性过滤深层嵌套路由数组并生成路径-标题Record?

处理嵌套路由生成路径-标题映射

问题描述

给定一个嵌套深度未知(可达到5层及以上)的路由对象数组,需要实现以下需求:

  • 过滤所有visible属性为true的路由记录
  • 生成以完整拼接路径为键、对应路由title为值的Record<string, string>映射

示例输入

const routes: RouteType[] = [
  {
    path: '/user', visible: true, title: 'User'
  },
  {
    path: "/admin", visible: true, title: "Admin", children: [
      {index: true, visible: false},
      {path: "dashboard", visible: true, title: "Dashboard"},
      {path: "changelog", visible: true, title: "Changelog"},
      {path: "profile", visible: true, title: "Profile"},
      {path: "settings", visible: true, title: "Settings", children: [
          {index: true, visible: false},
          {path: "themes", visible: true, title: "Theme"},
          {path: "themes/new", visible: true, title: "New"}
        ]
      }
    ]
  }
];

期望输出

const resultMap: Record<string, string> = {
  "/admin": "Admin",
  "/admin/dashboard": "Dashboard",
  "/admin/changelog": "Changelog",
  "/admin/profile": "Profile",
  "/admin/settings": "Settings",
  "/admin/settings/themes": "Theme",
  "/admin/settings/themes/new": "New"
};

解决方案

使用递归函数遍历嵌套路由,处理路径拼接和过滤逻辑:

完整代码

// 定义路由类型
type RouteType = {
  path?: string;
  index?: boolean;
  visible: boolean;
  title?: string;
  children?: RouteType[];
};

/**
 * 递归构建路由路径-标题映射
 * @param routes 路由数组
 * @param parentPath 父级路径,默认空字符串
 * @returns 路径-标题映射对象
 */
function buildRouteMap(routes: RouteType[], parentPath = ''): Record<string, string> {
  const map: Record<string, string> = {};

  routes.forEach(route => {
    // 过滤visible为false的项
    if (!route.visible) return;

    // 处理当前路由的完整路径
    let fullPath: string;
    if (route.index) {
      // index路由使用父路径
      fullPath = parentPath;
    } else if (route.path) {
      // 拼接父路径与当前路径,自动处理斜杠重复问题
      fullPath = `${parentPath}/${route.path}`.replace(/\/+/g, '/');
    } else {
      // 无path且非index的路由跳过
      return;
    }

    // 有title的项才加入映射
    if (route.title) {
      map[fullPath] = route.title;
    }

    // 递归处理子路由
    if (route.children && route.children.length > 0) {
      Object.assign(map, buildRouteMap(route.children, fullPath));
    }
  });

  return map;
}

// 示例调用
const resultMap = buildRouteMap(routes);
console.log(resultMap);

关键逻辑说明

  1. 递归遍历:通过递归处理children数组,支持任意深度的嵌套路由
  2. 路径处理:使用正则替换\/+/g自动合并重复斜杠,避免出现//dashboard这类无效路径
  3. 过滤逻辑:直接跳过visible: false的路由项
  4. Index路由处理:index路由使用父级路径作为完整路径,符合路由系统的常规逻辑
  5. 映射生成:仅当路由存在title时才加入结果,避免无效条目

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 02:51:24