javascript - 从嵌套对象数组返回类似文件夹的路径
问题描述
我有一组嵌套对象。它们代表类似文件夹的路径或带有子导航的菜单。
结构如下:
const MENU:Menu[] = [
{
value: 'Home',
nested: [
{ value: 'home-1', url: 'home-1' },
{ value: 'home-2', url: 'home-2' },
],
},
{
value: 'about',
nested: [
{
value: 'about-1',
url: 'about-1',
},
{
value: 'about-2',
url: 'about-2',
},
],
},
];
我希望给定的url使用value属性返回路径。
例如,对于home-1
=>['Home','home-1']
对于about-2
=>['about','about-2']
这个菜单的界面是
interface Menu {
value: string;
nested?: Menu[];
url?: string;
}
这是我尝试过的
function getPath(url, menu = MENU, navTreePath = []) {
for (let i = 0; i < menu.length; i++) {
const currentMenu = menu[i];
if (currentMenu.url === url) {
navTreePath.push(currentMenu.value);
return navTreePath;
} else if (currentMenu.nested) {
navTreePath.push(currentMenu.value);
return getNavTreePathFromUrl(url, currentMenu.nested, []);
} else {
}
}
}
和电话
const path = getPath('about-2');
解决方案
您将需要递归算法来爬取整个深度:
const menu = [
{
value: 'Home',
nested: [
{ value: 'home-1', url: 'home-1' },
{ value: 'home-2', url: 'home-2' },
],
},
{
value: 'about',
nested: [
{
value: 'about-1',
url: 'about-1',
},
{
value: 'about-2',
url: 'about-2',
nested: [
{
value: 'detailed about',
url: 'detailedAbout'
}
]
},
],
},
],
getPath = (tree, needle, path=[]) =>
tree.reduce((acc, {url, value, nested=[]}) => {
if(url == needle){
acc.push(...path, value)
} else if (!!nested.length) {
acc.push(...getPath(nested, needle, [...path, value]))
}
return acc
}, [])
console.log(getPath(menu, 'detailedAbout'))
推荐阅读
- templates - Netsuite 打印模板:无法访问实体字段
- reactjs - 使用 localStorage 在 React JS 中存储当前登录的用户数据
- c# - 使用 CSV 助手进行错误映射,一个字段的值为空
- node.js - 将标头发送给客户端后无法设置标头
- html - 字体真棒图标未显示在选择框中
- google-cloud-platform - Google Cloud Platform OAuth 应用程序验证问题
- wpf - (VB.NET) 对象引用未设置为对象的实例。无法解决问题
- ocaml - 如何在 OCaml 中结合函数的布尔和单位输出?
- html - 图像尺寸属性中允许哪些媒体条件?
- reactjs - 在 macos 上配置的 nginx 服务器中刷新时 react.js 应用程序显示 404