const tree = [{
id: 1,
children: [
{
id: 3,
children: [{
id: 5
}]
},
{
id: 4
}
]
},
{
id: 7,
children: [
{
id: 8
}
]
}
]
const arr = []
const getParentIds = function (id, tree, arr) {
for (const i = 0, length = tree.length; i < length; i++) {
const currentNode = tree[i]
if (currentNode.id === id) {
arr.push(id)
return true
} else {
if (currentNode.children && currentNode.children.length) {
const find = getParentIds(id, currentNode.children, arr)
if (find) {
arr.push(currentNode.id)
return true
}
} else {
return false
}
}
}
}
getParentIds(8, tree, arr)
console.log(arr)
根据某个节点的数据,向上查找所有的父级
于 2023-03-20 16:28:26 首次发布