树形数据找父节点
直接代码伺候
js
//数据格式如下
let arrData = [
{
id: '123',
name: '根节点',
children: [
{ id: '1234', name: '节点1', parent_id: '123' },
{
id: '12344',
name: '节点2',
parent_id: '123',
children: [
{ id: '123456', name: '节点2-1', parent_id: '12344' },
{ id: '1234477', name: '节点2-2', parent_id: '12344' },
],
},
],
},
]
//寻找父节点
function getParentNode(arr, func, ids = []) {
if (!arr) return []
for (let data of arr) {
ids.push(data.id)
if (func(data)) return ids
if (data.children) {
const findChildren = this.getParentNode(data.children, func, ids)
if (findChildren.length) return findChildren
}
ids.pop()
}
return []
},
//调用根据node找其所有父节点id
let node = { id: '123456', name: '节点2-1', parent_id: '12344' }
let arr = this.getParentNode(
allData,
(data) => data.id == node.parent_id
)
console.log(arr)