function getFullPath(val: string) {
let stack: any[] = treeData.map((item) => ({ path: [item.label], ...item }));
while (stack.length) {
const curr = stack.pop();
const { children, label, path } = curr;
if (label === val) {
return curr.path
} else if (children?.length) {
stack = [
...stack,
...children.map((item) => ({ ...item, path: path.concat(item.label) })),
];
}
}
}
上述代码是根据不重复的label进行处理的。下面附上来自elementui,el-tree的数据做测试;
const treeData = [
{
label: "一级 1",
children: [
{
label: "二级 1-1",
children: [
{
label: "三级 1-1-1",
},
],
},
],
},
{
label: "一级 2",
children: [
{
label: "二级 2-1",
children: [
{
label: "三级 2-1-1",
},
],
},
{
label: "二级 2-2",
children: [
{
label: "三级 2-2-1",
},
],
},
],
},
{
label: "一级 3",
children: [
{
label: "二级 3-1",
children: [
{
label: "三级 3-1-1",
},
],
},
{
label: "二级 3-2",
children: [
{
label: "三级 3-2-1",
},
],
},
],
},
];