首页 > 其他分享 >js递归查询id所对应的节点,查询该节点的父节点,查询该节点的所有子节点

js递归查询id所对应的节点,查询该节点的父节点,查询该节点的所有子节点

时间:2023-04-21 16:55:48浏览次数:35  
标签:null name list children 节点 查询 id

在工作项目中经常遇到树形结构的数据,而往往我们需要用递归来实现,下面就给大家列举常用的递归操作。    

let  treeList = [
 
        {
 
          id: '1',
 
          name: '父一',
 
          children: [
 
            {
 
              id: '1-1',
 
              name: '子一一',
 
              children: [
 
                { id: '1-1-1', name: '孙一一', children: null },
 
                { id: '1-1-2', name: '孙一二', children: null },
 
                { id: '1-1-3', name: '孙一三', children: null }
 
              ]
 
            }
 
          ]
 
        },
 
        {
 
          id: '2',
 
          name: '父二',
 
          children: [
 
            { id: '2-1', name: '子二一', children: null },
 
            { id: '2-2', name: '子二一', children: null },
 
            { id: '2-3', name: '子二一', children: null }
 
          ]
 
        },
 
        {
 
          id: '3',
 
          name: '父三',
 
          children: null
 
        }
 
      ]

一,根据id查询id所对应的对象

/*
*@param  需要遍历的数组
*@param  查询所需要的id
*/
function getObjById(list,id){
//判断list是否是数组
if(!list instanceof Array){
  return  null
}
 
//遍历数组
for(let i in list){
  let item=list[i]
  if(item.id===id)
  {
    return item
  }else{
     //查不到继续遍历
      if(item.children){
       let value=getObjById(item.children,id)
     //查询到直接返回
       if(value){
           return value
         }
    }
   
  }
 
 }
 
}
//测试
console.log(getObjById(treeList,"1-1-3"))
 

最后控制台打印:  { id: '1-1-3', name: '孙一三', children: null }  

 二,根据id查询本节点和所有父级节点

//根据id查询该节点和所有父级节点
 
function  getParentsById(list,id){
    for (let i in list) {
        if (list[i].id === id) {
 
           //查询到就返回该数组对象
           return [list[i]]
        }
 
        if (list[i].children) {
 
          let node = getParentsById(list[i].children, id)
          if (node !== undefined) {
              //查询到把父节点连起来
            return node.concat(list[i])
          }
        }
     }    
}
 
console.log(getParentsById(treeList,'2-3'))

最后控制台打印:   [{id: "2-3", name: "子二一", children: null}, {id: "2", name: "父二", children: Array(3)}]

三,根据id查询该节点和所有子节点

//需要用到上面的根据id查询该节点对象
function getObjById(list,id){
 //直接复制过来
  ...............
}
 
 
 
 // list 为已查询到的节点children数组,returnvalue为返回值(不必填)
function  getChildren (list,returnValue=[]) {
     for(let i in list){
      //把元素都存入returnValue
      returnValue.push(list[i])
      if (list[i].children) {
          getChildren(list[i].children, returnValue)
      }
     }
     return returnValue
 }
 
 
//age:
let obj=getObjById(treeList,"1")
if(obj&&obj.children){
   let childrenList=getChildren(obj.children)
   console.log(childrenList)
  } else {
    console.log("没有该节点或者没有子元素")
  }

最后控制台打印:

[ {id: "1-1", name: "子一一", children: Array(3)},

{id: "1-1-1", name: "孙一一", children: null},

{id: "1-1-2", name: "孙一二", children: null},

{id: "1-1-3", name: "孙一三", children: null}]


————————————————
版权声明:本文为CSDN博主「爱吃蛋炒饭加蛋」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_27104997/article/details/103617219

标签:null,name,list,children,节点,查询,id
From: https://www.cnblogs.com/caihongmin/p/17341012.html

相关文章

  • Invalid prop: type check failed for prop "defaultExpandAll". Expected Boolean, g
    vue中使用element-ui报错如下,defaultExpandAll关键词页面也搜不到[Vuewarn]:Invalidprop:typecheckfailedforprop"defaultExpandAll".ExpectedBoolean,gotStringwithvalue"true".foundin---><ElTable>atpackages/table/src/table.vue......
  • com.android.tools.r8.internal.Jc: Absent Code attribute in method that is no
    AbsentCodeattributeinmethodthatisnotnativeorabstract背景:在导入framework.jar时,报错。一般这种问题就是对应的jar包有问题。解决方式:将implementationfiles('libs\\framework.jar')修改为compileOnlyfiles('libs\\framework.jar')作者:黄志成_链接:https://ww......
  • Android Studio Gradle Download 慢/卡问题解决
    build.gradlebuildscript{repositories{//jcenter()//jcenter(){url'http://jcenter.bintray.com/'}maven{url'http://maven.aliyun.com/nexus/content/groups/public/'}maven{url"https://jitpac......
  • Android Studio类名冲突快捷键
    AndroidStudio类名搜索快捷键Ctrl+N。1.遇到问题2.解决问题直接在jar包里面把冲突的类删掉。......
  • MySQL Shell 使用报错 SyntaxError: Unexpected identifier
    文章目录一、问题报错二、解决办法一、问题报错MySQLShell8.0.23Copyright(c)2016,2021,Oracleand/oritsaffiliates.OracleisaregisteredtrademarkofOracleCorporationand/oritsaffiliates.Othernamesmaybetrademarksoftheirrespectiveowners.T......
  • IDEA 用上这款免费 GPT4 插件,生产力爆表了
    大家好,我是一航!早前给大家分享过GPT的一些玩法,但是依旧有很多铁子没有掌握魔法的奥秘,始终没有用上;前两天,一兄台分享给我一款IDE插件:Bito-ChatGPT,安装就能直接在IDE中使用GPT,就算是不会魔法,同样也能使用;最重要是免费使用,速度也非常可观!Bito-ChatGPT插件是一款基于GPT(Gen......
  • android 打包版本说明
    个人经验之谈,不对之处,也不用留言,我的知识都是实战中积累,别给我整那么多虚的理论#编译应用程序所采用的版本#人话:你的安卓包包含什么样的字节码,不做兼容,可能会崩溃PROP_COMPILE_SDK_VERSION=31#应用程序对系统的要求最低21#人话:你的应用对设备的最低要求PROP_MIN_SDK_VERSION=......
  • idea实现远程debug汇总
    idea实现远程debug,这个很实用的,可以实现发现并解决测试环境有问题,本地环境没有问题的情况。原理其实就是请求的时候远程的服务打到本地的,其实就是解决测试环境有问题,无法解决,需要通过本地debug的形式发现问题,这个其实很好用。参考博客:https://www.ngui.cc/el/1611042.html?action=......
  • nafxcw.lib(afxmem.obj) : error LNK2005: "void * __cdecl operator new(unsigned in
    在封装非MFC环境的静态库时调用了依赖MFC环境的静态库时编译测试程序报错如下:nafxcw.lib(afxmem.obj):errorLNK2005:"void*__cdecloperatornew(unsignedint)"(??2@YAPAXI@Z)已经在LIBCMT.lib(new.obj)中定义nafxcw.lib(afxmem.obj):errorLNK2005:"void*__cde......
  • Aras学习笔记 (53) - 根据ID快速找到文件Vault路径
    Step1:首先在对象类File中根据名称找到ID;Step2:右键文件-->Share-->CopyID;Step3:在Console中输入下命令:top.aras.IomInnovator.getFileUrl("[文件ID]",top.aras.Enums.UrlType.SecurityToken)结果如下: ......