利用递归的方式在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 后直接返回结果 跳出函数。

原文地址:https://www.cnblogs.com/buxiugangzi/p/12080333.html