js树结构数组根据子项的id查询父项的pid
时间: 2024-03-12 14:46:17 浏览: 63
可以通过遍历树结构数组来查询子项的父项,具体代码实现如下:
```javascript
/**
* 根据子项的id查询父项的pid
* @param {Array} treeData 树结构数组
* @param {String} childId 子项的id
* @return {String} 父项的pid
*/
function findParentPidById(treeData, childId) {
for (let i = 0; i < treeData.length; i++) {
const node = treeData[i]
if (node.id === childId) {
return node.pid
} else if (node.children && node.children.length > 0) {
const parentPid = findParentPidById(node.children, childId)
if (parentPid !== null) {
return parentPid
}
}
}
return null
}
```
调用方式如下:
```javascript
const treeData = [
{
id: '1',
pid: '0',
label: '一级菜单1',
children: [
{
id: '11',
pid: '1',
label: '二级菜单1-1',
},
{
id: '12',
pid: '1',
label: '二级菜单1-2',
},
],
},
{
id: '2',
pid: '0',
label: '一级菜单2',
children: [
{
id: '21',
pid: '2',
label: '二级菜单2-1',
},
{
id: '22',
pid: '2',
label: '二级菜单2-2',
children: [
{
id: '221',
pid: '22',
label: '三级菜单2-2-1',
},
],
},
],
},
]
const parentPid = findParentPidById(treeData, '221')
console.log(parentPid) // 22
```
阅读全文