利用遞歸的方式在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 后直接返回結果 跳出函數。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM