zoukankan      html  css  js  c++  java
  • 利用递归的方式在JSON 数据中找到某个节点的多有父节点

    在项目中遇到的问题-- 一个级联题,知道答案id  后将每一级的选项展示出来

    例如 级联题的 json 数据是

    [
      {
        name: '北京',
        id: 1,
        children:[
          {
            name: '朝阳',
            id: 3,
            children: [
              {
                name: '北京站',
                id: 9
              }
            ]
          },
          {
            name: '海淀',
            id: 4,
            children: [
              {
                name: '中关村',
                id: 10
              }
            ]
          }
        ]
    
      },
      {
        name:'河北',
        id:2,
        children:[
          {
            name: '张家口',
            id: 5,
            children:[
              {
                name: '宣化',
                id: 7
              }
            ]
          },
          {
            name: '石家庄',
            id: 6,
            children: [
              {
                name: '无极',
                id: 8
              }
            ]
          }
        ]
      }
    ]

    现在知道 获取到的最后一级答案 id 是10 将所有选中的菜单计算出来

    function getcascade (opts,opt,path) {
      if (path===undefined) {
        path = []
      }
      for(var i=0;i<opts.length;i++){
        var temPath = path.concat()
        temPath.push(opts[i].name)
        if (opt == opts[i].id){
          return temPath
        }
        if (opts[i].children){
          var findResult = getcascade(opts[i].children,opt,temPath)
          if (findResult){
            return findResult
          }
        }
      }
      
    }
    
    let list = getcascade(json,10)
    console.log(list)

    得到结果  

    [ '北京', '海淀', '中关村' ]

    该递归方法中用到了 数组的concat 方法 该方法连接两个数组 不改变原数组,

    在循环调用当中 遇到return 后直接返回结果 跳出函数。

  • 相关阅读:
    Windows10内置Linux子系统安装及C++编程环境配置
    在iOS平台上使用gtest进行单元测试
    【转载】Android7.0以前和7.0以后开启闪光灯的方式
    C++11 move记录
    决策树
    生成MTLLibrary
    【转载】3D显示技术
    vector::insert和std::copy
    Visual Studio 2017 + CMake + CUDA
    词嵌入向量WordEmbedding
  • 原文地址:https://www.cnblogs.com/buxiugangzi/p/12080333.html
Copyright © 2011-2022 走看看