js将树形数据展开成数组

今天因为开发需求,需要获取树形数据某一层的所有节点,在网上并未找到相似案例。

所以自己写了一个,写法拙劣,也是第一次写博客。大佬请指点

var tree = [{
                    id: 1,
                    child: [{
                        id: 2,
                        child: [{
                            id: 3,
                            child: [{
                                id: 10
                            }]
                        }]
                    }]
                }, {
                    id: 4,
                    child: [{
                        id: 5,
                        child: [{
                            id: 6
                        }]
                    }]
                }, {
                    id: 7,
                    child: [{
                        id: 8,
                        child: [{
                            id: 9
                        }]
                    }]
                }]

                function treeLayers(tree, index) {
                    var stark = []
                    stark = stark.concat(tree)
                    var now_l = 0 //当前层数
                    var layerArr = [] //储存每层的数组
                    while (stark.length) {
                        var temp = stark.shift();
                        if (typeof temp === "number") {
                            //开始下一层
                            console.log(temp)
                            now_l = temp
                            continue
                        }
                        if (temp.child) {
                            stark = stark.concat([now_l + 1], temp.child);
                        }
                        if (layerArr[now_l] === undefined) {
                            layerArr[now_l] = []
                        }
                        layerArr[now_l].push(temp)
                    }
                    return layerArr[index]
                }

                let res = treeLayers(tree, 3)

                res[0].id = 11111

                console.log(res)

                console.log(tree[0].child[0].child[0].child[0])

 

posted @ 2022-03-23 17:49  梵幽  阅读(611)  评论(0)    收藏  举报