const cityData = [
{
id: 'axzx',
name: '广东省',
children: [
{
id: 'sdsd',
name: '深圳市',
children: [
{
id: '45dss',
name: '南山区'
},
{
id: 'sdsd11',
name: '福田区',
children: [{
id: 'ddrr2',
name: 'A街道'
}]
}
]
},
{
id: '2323d',
name: '东莞市',
children: [
{
id: 'xxs2',
name: 'A区'
},
{
id: 'kklio2',
name: 'B区',
}
]
}
]
}];
function getPathById(cityData, id){
//定义变量保存当前结果路径
let temppath = [];
try {
function getNodePath(node) {
temppath.push(node.name);
// console.log('==========',temppath)
//找到符合条件的节点,通过throw终止掉递归
if (node.id === id) {
throw ('GOT IT!');
}
if (node.children && node.children.length > 0) {
for (let i = 0; i < node.children.length; i++) {
getNodePath(node.children[i]);
}
//当前节点的子节点遍历完依旧没找到,则删除路径中的该节点
temppath.pop();
} else {
//找到叶子节点时,删除路径当中的该叶子节点
temppath.pop();
}
}
getNodePath(cityData);
} catch (e) {
console.log(temppath)
}
}
getPathById(cityData.shift(), 'sdsd11')
js 树查找
于 2022-03-17 15:28:39 首次发布