JS 查找数组的父节点及祖先节点

function findAllParent(node, tree, parentNodes=[], index = 0){
    if(!node || node.parentId === 0){
        return
    }
    findParent(node, parentNodes, tree)
    let parntNode = parentNodes[index]
    findAllParent(parntNode, tree, parentNodes, ++index)
    return parentNodes
}

function findParent(node, parentNodes, tree){
    for(let i=0; i< tree.length; i++){
        let item = tree[i]
        if(item.id === node.parentId){
            parentNodes.push(item)
            return
        }
        if(item.children && item.children.length >0){
            findParent(node,parentNodes, item.children)
        }
    }
}

export default findAllParent

 

posted @ 2019-06-14 15:15  wavemelody  阅读(4744)  评论(1编辑  收藏  举报