const testData = [
{
value: '1',
label: 'Level one 1',
children: [
{
value: '1-1',
label: 'Level two 1-1',
children: [
{
value: '1-1-1',
label: 'Level three 1-1-1',
},
],
},
],
},
{
value: '2',
label: 'Level one 2',
children: [
{
value: '2-1',
label: 'Level two 2-1',
children: [
{
value: '2-1-1',
label: 'Level three 2-1-1',
},
],
},
{
value: '2-2',
label: 'Level two 2-2',
children: [
{
value: '2-2-1',
label: 'Level three 2-2-1',
},
],
},
],
},
{
value: '3',
label: 'Level one 3',
children: [
{
value: '3-1',
label: 'Level two 3-1',
children: [
{
value: '3-1-1',
label: 'Level three 3-1-1',
},
],
},
{
value: '3-2',
label: 'Level two 3-2',
children: [
{
value: '3-2-1',
label: 'Level three 3-2-1',
},
],
},
],
},
];
## 递归实现
const getCurrentPath = (node, keyword) => {
const result = [];
const exec = (node, path) => {
const currentPath = path.concat(node.label);
if (node.label.search(keyword) !== -1) {
result.push(currentPath);
}
if (Reflect.has(node, 'children') && node.children.length > 0) {
node.children.forEach(child => {
exec(child, currentPath);
});
}
}
exec(node, []);
return result
}
testData.forEach(item => {
console.log(getCurrentPath(item, 'Level three 2-1-1'));
})