满口金牙 2022-06-05 01:49 采纳率: 91.5%
浏览 738
已结题

js 数组中多层嵌套对象,怎么递归取得,某id 对象的路径

数组中多层嵌套对象,怎么递归取得,某id 对象的路径

  const arr =[
    { id:'1',
      title:'a',
      children:[
        {id:'33',
         title:'axx',
         children:[{ id:'121111',title:'hh'},] 
        },
        {id:'34',title:'xxddf',}
      ]
    },
    { id:'2',title:'bxx'}
     //  略...
  ]
 // 找出 id为 121111 对象的路径, 返回一个数组: [第一层的 title,第三层的title ,第n层的 title ,自已的 title]

下面这样写不行,只能找到自已这层,没有父级路径


  function pathCompute(arr, key, path = []){
    for( let i = 0, len = arr.length; i < len; i++){
      path.push(arr[i].title)
      if( arr[i].key === key){
         console.log('找到了', path)
         return path
      } else if(arr[i].children && arr[i].children.length >= 1){
        pathCompute(arr[i].children, key, path)
      } else {
        path = [] // 没找到就清空数组,下循环重新写路径,但这样写不行
      }
    }
  }



  • 写回答

3条回答 默认 最新

  • 关注

    你题目的解答代码如下:

      const arr =[
        { id:'1',
          title:'a',
          children:[
            {id:'33',
             title:'axx',
             children:[{ id:'121111',title:'hh'},] 
            },
            {id:'34',title:'xxddf',}
          ]
        },
        { id:'2',title:'bxx'}
         //  略...
    ]
    // 找出 id121111 对象的路径, 返回一个数组: [第一层的 title,第三层的title ,第n层的 title ,自已的 title]
     
    function pathCompute(arr, key, path = []){
        for( let i = 0, len = arr.length; i < len; i++){
            path.push(arr[i].title);
            if( arr[i].id === key){
                console.log('找到了');
                return path;
            } else if(arr[i].children && arr[i].children.length >= 1){
                if(pathCompute(arr[i].children, key, path)!=false)
                    return path;
              }
            path.pop();
        }
        return false;
    }
    console.log(pathCompute(arr, '121111')); 
    

    如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!

    img

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 6月16日
  • 已采纳回答 6月8日
  • 创建了问题 6月5日

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来