树形数据
data: [
{
value: 'beijing',
label: '北京',
children: [
{
value: 'gugong',
label: '故宫'
},
{
value: 'tiantan',
label: '天坛'
},
{
value: 'wangfujing',
label: '王府井'
}
]
}
]
方法定义
/**
* 显示层级数据
* @param tree {Array} 树数据
* @param func {Function} 回调函数
* @param key{String} 指定返回字段名称
* @param path {Array} 路径数据
* @returns {*[]|[]|*}
*/
function treeFindPath(tree, func, key= "", path = []) {
if (!tree) return []
for (const data of tree) {
key=== "" ? path.push(data) : path.push(data[key]);
if (func(data)) return path
if (data.children && data.children.length) {
const findChildren = treeFindPath(data.children, func, key, path)
if (findChildren.length) return findChildren
}
path.pop()
}
return []
},
方法调用
const cId = "wangfujing"; //最底层级的key
let arr = this.treeFindPath(cities, data => data.value === cId, "label");
log(arr) //打印返回数据 ["北京","王府井"]