13const tree = {
id: 1,
name: "中国",
children: [
{
id: 2, name: "北京市", children: [
{ id: 3, name: "朝阳区", children: [] },
{ id: 4, name: "海淀区", children: [] },
]
},
{
id: 5, name: "上海市", children: [
{ id: 6, name: "徐汇区", children: [] },
{ id: 7, name: "黄浦区", children: [] },
]
},
]
}
function findPathById(id, Tree) {
let res = []
function get(tree, arr = []) {
Array.isArray(tree) && tree.forEach(val => {
let arrX = JSON.parse(JSON.stringify(arr)) //拷贝一下数组
arrX.push(val.name)
val.id === id ? (res = arrX) : val.children && get(val.children, arrX)
})
}
get([Tree])
return res.join(",")
}
const str = findPathById(4, Tree)