zoukankan      html  css  js  c++  java
  • 记一个JS树结构路径查找

    var a=[ {   "id" : "0000", "text" : "R1", "children" : [ {   "id" : "8978", "text" : "Aad",    "children" : [ {   "id" : "2312", "text" : "adaada", "children" : [ {   "id" : "5154", "text" : "asdsa"   }] },{    "id" : "4544", "text" : "afasf",  "children" : [ {   "id" : "5236", "text" : "afasf"   }, {   "id" : "2328", "text" : "afasf"   } ]    }] }, {   "id" : "7867", "text" : "R2", "children" : [ {   "id" : "8767", "text" : "afasf",  "children" : [ {   "id" : "2016", "text" : "afafa"   }, {   "id" : "2017", "text" : "afasd"   } ]    }, {   "id" : "7657", "text" : "h",  "children" : [ {   "id" : "7867", "text" : "afras"   } ]    } ]    } ]    } ];
        function buildArray(arrOrigin, id){
            var arr = [] // 操作数组
                ,re =[] // 结果  AND 是否匹配到
                ,run = true // 运行
    
            // arrOrigin 解析
            arrOrigin.map(e=> {
                arr.push({
                    id: e.parent_id,
                    children: [e],
                    nextFuncTag: true, // 下一个函数的起点标识
                })
            })
        
            /**
             * 组查询 (无状态函数)
             * @e{Array} 下一个元素
             */
            function select(e){
                if(!run)return
                // 截取段落
                e.nextFuncTag && (re = [])
                if(typeof(e.id)!="undefined")
                {
                    re.push(e.id);
                }
            
                if(e.id == id){
                    run = false
                }else// 下一级查询
                    if(e.children && e.children.length != 0){
                        e.children.map(select)
                    }
            }
    
            arr.map(select) 
    
            return re
        }
        console.log(buildArray(a, 2312));//["0000", "8978", "2312"]

      

  • 相关阅读:
    Git的初步学习
    Git的初步学习
    微信小程序我的界面
    微信小程序我的界面
    Day2:html和css
    Day2:html和css
    Day1:html和css
    Day1:html和css
    Java之JDK7的新语法探索
    Java之JDK7的新语法探索
  • 原文地址:https://www.cnblogs.com/sunshine-wy/p/9294059.html
Copyright © 2011-2022 走看看