美文网首页
树结构通过节点id返回所有父节点id(也可以返回name)

树结构通过节点id返回所有父节点id(也可以返回name)

作者: 扶得一人醉如苏沐晨 | 来源:发表于2022-11-16 10:18 被阅读0次
    // 根据子id找父id,返回值不包含查找的id
    function findParentsId (treeData, id) {
        if(treeData.length == 0) return
        for(let i = 0; i < treeData.length; i++) {
            if(treeData[i].id == id) {
                return []
            }else{
                if(treeData[i].children) {
                    let res = findParentsId(treeData[i].children, id)
                    if(res !== undefined) {
                        //这里也可以返回树节点的name
                        return res.concat(treeData[i].id).reverse()
                    }
                }
            }
        }
    }
     
    // 组织结构子id,找父id
    export const orgChildIdFindParent = (childId, orgList = []) => {
        const result = findParentsId(orgList, childId).concat(childId)
        return result || []
    }
     
    // 使用
    console.log(orgChildIdFindParent(1, list))
    

    相关文章

      网友评论

          本文标题:树结构通过节点id返回所有父节点id(也可以返回name)

          本文链接:https://www.haomeiwen.com/subject/aavsxdtx.html