2 回答
TA贡献1811条经验 获得超5个赞
这就是我的做法 - 首先根据.topic权限是否包含来过滤父数组,然后迭代具有数组的结果submenu并将子数组属性重新分配给过滤后的版本:
const permissions = ['search', 'reports', 'whitelist'];
permissions.push('all');
const menus=[{text:"Navigation",link:"navigation",topic:"all"},{text:"Dictionary",link:"dict",topic:"src"},{text:"Services",link:"/services",submenu:[{text:"Check company",link:"/services/search",topic:"search"},{text:"Report statistic",link:"/services/reportstatistic",topic:"another-topic"},{text:"Report request",link:"/services/getrequestreport",topic:"another-topic-2"},{text:"Get whitelist",link:"/services/getresponsereport",topic:"whitelist"},{text:"Get data",link:"/services/requestdata",topic:"reports"}]}];
const filteredMenus = menus.filter(
item => !item.topic || permissions.includes(item.topic)
);
filteredMenus
.filter(item => item.submenu)
.forEach(item => item.submenu = item.submenu.filter(
subitem => permissions.includes(subitem.topic)
));
console.log(filteredMenus);
TA贡献1811条经验 获得超4个赞
您可以使用Array.reduce处理menus数组,检查主题是否all包含在 中permissions,并根据相同的规则过滤子菜单值:
const permissions = ['search', 'reports', 'whitelist'];
const menus=[{text:"Navigation",link:"navigation",topic:"all"},{text:"Dictionary",link:"dict",topic:"src"},{text:"Services",link:"/services",submenu:[{text:"Check company",link:"/services/search",topic:"search"},{text:"Report statistic",link:"/services/reportstatistic",topic:"another-topic"},{text:"Report request",link:"/services/getrequestreport",topic:"another-topic-2"},{text:"Get whitelist",link:"/services/getresponsereport",topic:"whitelist"},{text:"Get data",link:"/services/requestdata",topic:"reports"}]}];
const includeMenu = (menu) => menu.topic == 'all' || permissions.includes(menu.topic);
const newArr = menus.reduce((c, m) => {
if (m.submenu) {
submenus = m.submenu.filter(includeMenu);
if (submenus.length) {
c.push({
text: m.text,
link: m.link,
submenu: submenus
});
}
} else if (includeMenu(m)) {
c.push(m);
}
return c;
}, []);
console.log(newArr);
添加回答
举报