知道树的最后一级和原始数据递归出前几级
数据源
const options = [
{
value: 'zhejiang',
label: 'Zhejiang',
children: [
{
value: 'hangzhou',
label: 'Hangzhou',
children: [
{
value: 'xihu',
label: 'West Lake',
},
],
},
],
},
{
value: 'jiangsu',
label: 'Jiangsu',
children: [
{
value: 'nanjing',
label: 'Nanjing',
children: [
{
value: 'zhonghuamen',
label: 'Zhong Hua Men',
},
],
},
],
},
];
let result = [],
tempArry = [];
const arryMap = (arry, code) => {
arry.map((item, index) => {
if (item.children) {
tempArry.push(item.value);
arryMap(item.children, code);
} else if (item.value == code) {
tempArry.push(item.value);
result = [...tempArry];
}
if (index == arry.length - 1) {
tempArry.pop();
}
});
}
arryMap(options, 'zhonghuamen');
console.log(result);
结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/006e317c8a014560029db6509bda519a.png)