如果菜单名称包含在允许的菜单字符串数组中,则筛选深度嵌套菜单数组



你好,我正在尝试将此菜单筛选为允许的菜单我的菜单结构如下:

const routes = [
{
path: '/dashboard',
name: 'dashboard',
children: [
{
path: '/style-guide',
name: 'style_guide',
},
],
},
{
path: '/tables-management',
name: 'tables_management',
children: [
{
path: '/auxiliary',
name: 'auxiliary',
children: [
{
path: '/reporting-code',
name: 'reporting_code',
},
{
path: '/budget-levels',
name: 'budget_levels',
},
{
path: '/qr-codes',
name: 'qr_codes',
},
{
path: '/error-code',
name: 'error_code',
},
],
},
},
];

这是允许的路线

const pages= ["style_guide", "reporting_code", "qr_codes"]

如果有任何子,我想过滤页面阵列中包含的路由,而不隐藏父路由

因此,结果应该显示仪表板路由,因为style_guide是一个可见的子

我试着这么做,但它的回报比预期的要多

const filter = (arr => {
return arr.filter(obj => {
if (obj.children && obj.children.length) {
return filter(obj.children);
}
return !!(obj.name && pages.includes(obj.name));
});
});

我错过了什么?实现它的最佳方法是什么不管怎样,传播运营商对它?

感谢

您需要减少数组,因为filter不会更改子数组。

对于不改变数据的方法,您需要创建新的对象。

const
getAllowed = (routes, pages) => routes.reduce((r, o) => {
if (pages.includes(o.name)) {
r.push(o);
} else if (o.children) {
let children = getAllowed(o.children, pages);
if (children.length) r.push({ ...o, children });
}
return r;
}, []),
routes = [{ path: '/dashboard', name: 'dashboard', children: [{ path: '/style-guide', name: 'style_guide' }] }, { path: '/tables-management', name: 'tables_management', children: [{ path: '/auxiliary', name: 'auxiliary', children: [{ path: '/reporting-code', name: 'reporting_code' }, { path: '/budget-levels', name: 'budget_levels' }, { path: '/qr-codes', name: 'qr_codes' }, { path: '/error-code', name: 'error_code' }] }] }],
pages = ["style_guide", "reporting_code", "qr_codes"],
result = getAllowed(routes, pages);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

最新更新