记一个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"]

 

  

 

posted @ 2018-07-11 13:44  顾星河  阅读(945)  评论(0编辑  收藏  举报