我需要检查的值
url
存在于
path
属性位于以下树的任何对象或节点中。
关于这棵树。这个
children
属性是可选的,但如果它存在,则可以无限期扩展
这棵树看起来与下面的相似
const items = [
{
path: "/admin/dashboard",
menuIcon: {
icon: "dashboard",
title: "toolbar.dashboard",
},
// children: [
// {
// path: "/admin/collection",
// menuIcon: {
// icon: "summarize",
// title: "toolbar.reports",
// },
// },
// ],
},
{
path: "/admin/contents",
menuIcon: {
icon: "archive",
title: "toolbar.contents",
},
},
{
path: "/admin/cigar-house-management",
menuIcon: {
icon: "home",
title: "toolbar.directory-management",
},
children: [
{
path: "/admin/reports",
menuIcon: {
icon: "summarize",
title: "toolbar.reports",
},
children: [
{
path: "/admin/admin-reports",
menuIcon: {
icon: "summarize",
title: "toolbar.reports",
},
},
],
},
],
},
];
为了达到预期效果,我使用以下功能
function isValid(url, tree) {
if (tree && Array.isArray(tree) && tree.length > 0) {
for (const node of tree) {
if (node.path === url) {
return true;
}
if (!node.children) {
continue;
}
const found = isValid(url, node.children);
if (found) {
return found;
}
return false;
}
}
}
可以在这里查看
const url = "/admin/admin-reports";
const items = [
{
path: "/admin/dashboard",
menuIcon: {
icon: "dashboard",
title: "toolbar.dashboard",
},
// children: [
// {
// path: "/admin/collection",
// menuIcon: {
// icon: "summarize",
// title: "toolbar.reports",
// },
// },
// ],
},
{
path: "/admin/contents",
menuIcon: {
icon: "archive",
title: "toolbar.contents",
},
},
{
path: "/admin/cigar-house-management",
menuIcon: {
icon: "home",
title: "toolbar.directory-management",
},
children: [
{
path: "/admin/reports",
menuIcon: {
icon: "summarize",
title: "toolbar.reports",
},
children: [
{
path: "/admin/admin-reports",
menuIcon: {
icon: "summarize",
title: "toolbar.reports",
},
},
],
},
],
},
];
function isValid(url, tree) {
if (tree && Array.isArray(tree) && tree.length > 0) {
for (const node of tree) {
if (node.path === url) {
return true;
}
if (!node.children) {
continue;
}
const found = isValid(url, node.children);
if (found) {
return found;
}
return false;
}
}
}
const output = isValid(url, items);
console.log(output);
但我注意到,当添加一个新节点(如树示例中的注释节点)时,例如作为第一个节点的子节点时,它不会计算父节点之后的节点。
此外,递归对我来说通常很困难,所以我很感激你的建议。
提前感谢