TypeScript父子结构数组:匹配子项URL激活父菜单问询
解决方案
方法一:直接修改原数组
遍历菜单数组,检查每个父级菜单的子项是否包含目标URL,匹配时设置父菜单的isActive为true,同时递归处理深层嵌套的子菜单(支持多级菜单场景):
function setParentMenuActive(menu: IMenuItem[], targetUrl: string): void { menu.forEach(item => { if (item.items) { // 检查当前父菜单的子项是否有匹配的URL const hasMatchingChild = item.items.some(child => child.url === targetUrl); if (hasMatchingChild) { item.isActive = true; } // 递归处理子菜单中的父级项(支持多级嵌套) setParentMenuActive(item.items, targetUrl); } }); } // 调用函数,传入目标URL 'agama' setParentMenuActive(hrdMenu, 'agama');
方法二:返回新数组(Immutable 方式)
如果不想修改原数组(比如在React等需要状态不可变的框架中),可以通过映射和递归返回全新的菜单数组:
function updateParentMenuActive(menu: IMenuItem[], targetUrl: string): IMenuItem[] { return menu.map(item => { const updatedItem = {...item}; if (updatedItem.items) { // 先递归更新子菜单 const updatedItems = updateParentMenuActive(updatedItem.items, targetUrl); // 检查更新后的子项是否存在目标URL const hasMatchingChild = updatedItems.some(child => child.url === targetUrl); if (hasMatchingChild) { updatedItem.isActive = true; } updatedItem.items = updatedItems; } return updatedItem; }); } // 调用函数得到更新后的菜单数组 const updatedHrdMenu = updateParentMenuActive(hrdMenu, 'agama');
说明
- 两种方法都支持多级嵌套菜单的场景,即使子菜单下还有更深层级的父菜单,也能正确匹配并设置
isActive。 - 方法一直接修改原数组,性能更优;方法二保持原数组不变,适合需要状态管理的场景。
内容的提问来源于stack exchange,提问作者Fadly Dzil
相关产品推荐
相关产品推荐

