js获取树形结构的所有子节点和父节点

js获取树形结构的所有子节点和父节点


let datasource = [
{
  path: "/nested",
   title: "Nested",
   children: [
   {
     path: "/nested/menu1",
     title: "Menu1",
     children: [
       {
         path: "/nested/menu1/menu1-1",
         title: "Menu1-1"
       },
       {
         path: "/nested/menu1/menu1-2",
         title: "Menu1-2"
       },
       {
         path: "/nested/menu1/menu1-3",
         title: "Menu1-3"
       },
     ]
  },
   {
     path: "/nested/menu2",
     title: "Menu2",
   }
   ]
   }
 ]


 const targetData = {};
 function loops(data = [], parent) {
 return data.map(({ children, title: value }) => {
 const node = {
 value,
 parent
 }
 targetData[value] = node;
 node.children = loops(children, node);
 return
 })
 }

 function getNode(value) {
   let node = [];
   let currentNode = targetData[value];
   node.push(currentNode.value);
   if (currentNode.parent) 
  {
     return node
  }
 loops(datasource)
 //获取父节点
 const target = getNode('Menu1-3')
 console.log(target)
}
//获取某节点的所有子节点
getChild(nodes, item, arr) {
    for (let el of nodes) {
        if (el.nodeId === item) {
            arr.push(el.nodeId);
            if (el.children) {
                this.childNodesDeep(el.children, arr);
            }
        } else if (el.children) {
            this.getChild(el.children, item, arr);
        }
    }
    return arr;
},
childNodesDeep(nodes, arr) {
    if (nodes)
        nodes.forEach((ele) => {
            arr.push(ele.nodeId);
            if (ele.children) {
                this.childNodesDeep(ele.children, arr);
            }
        });
}
//获取某节点的所有子节点
getChild(nodes,item,arr){
  for(let el of nodes){
      if(el.pid === item){
          arr.push(el.id);
          if(el.children){
              this.childNodesDeep(el.children,arr);
          }
      }else if(el.children){
          this.getChild(el.children,item,arr);
      }
  }
  return arr;
},
childNodesDeep(nodes,arr){
  if(nodes){
      nodes.forEach((ele) => {
          arr.push(ele.id);
          if(ele.children){
              this.childNodesDeep(ele.children,arr);
          }
      })
  }
}

参考原文链接
参考原文链接

posted @   季风时节  阅读(2802)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示