var arr = [
{
id: '1',
children: [
{
pid: 1,
id: '1_1',
children: [
{
pid: '1_1',
id: '1_1_1',
children: []
}
]
},
{
pid: 1,
id: '1_2',
children: [
{
pid: '1_2',
id: '1_2_1',
children: [
{ pid: '1_2_1', id: '1_2_1_1' },
{ pid: '1_2_1', id: '1_2_1_2' },
{ pid: '1_2_1', id: '1_2_1_3' }
]
}
]
},
{
pid: 1,
id: '1_3',
children: [
{
pid: '1_3',
id: '1_3_1',
children: []
}
]
},
{
pid: 1,
id: '1_4',
children: [
{
pid: '1_4',
id: '1_4_1',
children: []
}
]
}
]
}
]
function getDataTree(arr, target) {
let res = null
for (let i = 0; i < arr.length; i++) {
const item = arr[i]
const { id, children } = item
if (target === id) {
return item
} else if (children?.length) {
res = getDataTree(children, target)
if (res) break
}
}
return res
}
const res = getDataTree(arr, '1_3_1')
console.log('res: ', res)
目前只能获取到 指定 id
的当前 node
和 子节点
,
请问怎么获取它的完成的父节点
和 当前节点
以及 子节点
?
也就是
[
{
id: '1',
children: [
{
pid: 1,
id: '1_3',
children: [
{
pid: '1_3',
id: '1_3_1',
children: []
}
]
}
]
}
]
进阶一下:如果没有 pid
是否能获取到父节点?
pid 其实没有用,冗余信息。