首页 新闻 会员 周边 捐助

给一个id,获取它在树中的id的数组

0
[待解决问题]
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"   } ]    } ]    } ]    } ];
给定一个id例如位id=2312;
我们要获取到的是
ids=[0000,8978,2312]
一叶*秋的主页 一叶*秋 | 初学一级 | 园豆:5
提问于:2018-07-11 10:44
< >
分享
所有回答(2)
0
    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"]

网上搜了一下树结构的路径查找,稍稍修改了一下,亲测有效

顾星河 | 园豆:7281 (大侠五级) | 2018-07-11 13:30
0

你不是问过了吗?

xiaohc | 园豆:23 (初学一级) | 2018-07-12 13:30
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册