JS 递归函数来遍历菜单树 2

在 JavaScript 中,你可以编写一个通用的递归函数来遍历树形结构(如菜单),并支持对每个节点进行修改、新增字段、过滤、删除、替换等操作。下面是一个灵活的递归菜单处理方法,它接收一个菜单数组和一个配置对象,该配置对象可以定义你想要执行的操作。


✅ 示例:通用递归菜单处理器

/**
 * 递归处理菜单树
 * @param {Array} menu - 菜单数据,数组形式,每个项可能包含 children 字段
 * @param {Object} options - 配置选项
 * @param {Function} [options.transform] - 修改/新增字段:(node, path) => newNode | undefined(返回新节点或 undefined 表示删除)
 * @param {Function} [options.filter] - 过滤条件:(node, path) => boolean(返回 false 则删除该节点及其子树)
 * @returns {Array} 处理后的新菜单(不修改原数据)
 */
function processMenu(menu, options = {}) {
  const { transform, filter } = options;

  function walk(nodes, path = []) {
    if (!Array.isArray(nodes)) return [];

    const result = [];
    for (let i = 0; i < nodes.length; i++) {
      const node = nodes[i];
      const currentPath = [...path, i];

      // 如果有 filter 且返回 false,则跳过该节点(包括子树)
      if (filter && !filter(node, currentPath)) {
        continue;
      }

      // 深拷贝节点(避免修改原始数据)
      let newNode = JSON.parse(JSON.stringify(node));

      // 应用 transform
      if (transform) {
        const transformed = transform(newNode, currentPath);
        if (transformed === undefined) {
          // 返回 undefined 表示删除该节点
          continue;
        }
        newNode = transformed;
      }

      // 递归处理 children
      if (newNode.children && Array.isArray(newNode.children)) {
        newNode.children = walk(newNode.children, [...currentPath, 'children']);
        // 可选:如果 children 为空,是否删除 children 字段?
        // if (newNode.children.length === 0) delete newNode.children;
      }

      result.push(newNode);
    }
    return result;
  }

  return walk(menu);
}

🔧 使用示例

假设原始菜单如下:

const menu = [
  {
    id: 1,
    name: '首页',
    path: '/home'
  },
  {
    id: 2,
    name: '系统管理',
    children: [
      { id: 3, name: '用户管理', path: '/user' },
      { id: 4, name: '角色管理', path: '/role' }
    ]
  },
  {
    id: 5,
    name: '无效菜单',
    disabled: true
  }
];

1. 新增字段(比如加 label)

const newMenu = processMenu(menu, {
  transform(node) {
    node.label = node.name; // 新增字段
    return node;
  }
});

2. 修改字段

const newMenu = processMenu(menu, {
  transform(node) {
    if (node.path) {
      node.path = node.path.toUpperCase(); // 转大写
    }
    return node;
  }
});

3. 删除某些节点(通过 filter 或 transform 返回 undefined)

  • 使用 filter 删除禁用项:
const newMenu = processMenu(menu, {
  filter(node) {
    return !node.disabled; // 过滤掉 disabled 为 true 的项
  }
});
  • 使用 transform 删除特定项:
const newMenu = processMenu(menu, {
  transform(node) {
    if (node.id === 5) return undefined; // 删除 id=5 的项
    return node;
  }
});

4. 组合操作:过滤 + 修改 + 新增

const newMenu = processMenu(menu, {
  filter: (node) => !node.disabled,
  transform: (node) => {
    node.key = node.id;           // 新增 key
    node.title = node.name;       // 改名
    delete node.name;             // 删除原字段
    return node;
  }
});

⚠️ 注意事项

  • 本方法使用 JSON.parse(JSON.stringify(...)) 实现深拷贝,适用于纯对象(不含函数、Date、RegExp 等)。如有复杂数据,建议使用 structuredClone(现代浏览器)或 lodash 的 cloneDeep。
  • path 参数可用于调试或根据路径做特殊处理(如只修改某一层)。
  • 所有操作不会修改原始菜单,而是返回新数组。

如果你有更具体的需求(比如只改某一层、按 ID 查找后修改等),也可以扩展这个函数。需要我帮你写一个“根据 ID 修改节点”的专用方法吗?

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容