JS查找树上某个节点的父节点 兄弟节点 以及子节点

获取某个节点的所有父节点:

function getAllParentNodes(list, id) {
  for(let i in list) {
    if(list[i].resourcesId === id) {
      return [list[i]].filter(v => v.resourcesId !== id)
    }
    if(list[i].children?.length > 0) {
      let node = getAllParentNodes(list[i].children, id)
      if(node) return node.concat(list[i]).filter(v => v.resourcesId !== id)
    }
  }
}

 

获取某个节点的兄弟节点:

function getBrotherNodes(list, id) {
  for(let i in list) {
    if(list[i].resourcesId === id) {
      return list.filter(v => v.resourcesId !== id)
    }
    if(list[i].children?.length > 0) {
      let node = getBrotherNodes(list[i].children, id)
      if(node) return node.filter(v => v.resourcesId !== id)
    }
  }
}

  

获取某个节点的所有子节点:

function getAllChildrenNodes(list, id, arr = []) {
  for(let i in list) {
    if(list[i].resourcesId === id) {
      arr.push(list[i])
      if(list[i].children?.length > 0) {
        getChild(list[i].children, arr)
      }
    }else {
      if(list[i].children?.length > 0) {
        getAllChildrenNodes(list[i].children, id, arr)
      }
    }
  }
  return arr.filter(v => v.resourcesId !== id)
}
function getChild(list,  arr) {
  list.forEach(v => {
    arr.push(v)
    if(v.children) {
      getChild(v.children, arr)
    }
  })
}

  

数据:

let list = [
  {
    label: '最外层1',
    resourcesId: '1',
    children: [
      {
        label: '第二层1',
        resourcesId: '1-1',
        children: [
          {
            label: '第三层1',
            resourcesId: '1-1-1',
            children: [
              {
                label: '第四层1',
                resourcesId: '1-1-1-1'
              },{
                label: '第四层2',
                resourcesId: '1-1-1-2'
              }
            ]
          },{
            label: '第三层2',
            resourcesId: '1-1-2'
          },{
            label: '第三层3',
            resourcesId: '1-1-3'
          }
        ]
      },{
        label: '第二层2',
        resourcesId: '1-2'
      }
    ]
  }
]

  

 resourcesId 为 '1-1' label 为 '第二层1' 的为例

let a = getAllChildrenNodes(list, '1-1')   //子节点
let b = getAllParentNodes(list, '1-1')  //父节点
let c = getBrotherNodes(list, '1-1')  //兄弟节点
console.log(a);
console.log(b);
console.log(c);

  

a b c 打印出来的数据:

(如果想要返回的数据包括当前节点,把 filter 方法去掉即可.)

posted @ 2022-08-15 16:31  环岛公路  阅读(3768)  评论(0编辑  收藏  举报