现有数据结构
let list = [
{
key: '/a',
children: [
{
key: 'b',
chilren: [
{
key: '/c',
children: [
{
key: '/d',
}
]
}
]
}
]
},
{
key: '/a1',
children: [
{
key: 'b1',
chilren: [
{
key: '/c1',
children: [
{
key: '/d1',
}
]
}
]
}
]
}
]
要求根据/c1
找到最顶端的key。
方法如下:
const findTopKey = (list, targetKey) => {
for (const root of list) {
if (findInTree(root, targetKey)) {
return root.key;
}
}
return null;
}
const findInTree = (node, targetKey) => {
if (node.key === targetKey) {
return true;
}
if (node.children) {
for (const child of node.children) {
if (findInTree(child, targetKey)) {
return true;
}
}
}
return false;
}
const parentKey = findTopKey(items.value, activeMenu?.value[0]);