js展开一颗树

WEB前端 waitig 485℃ 百度已收录 0评论

Tree View 指令不支持树结构数据源,只支持单层数组。(也许是我没发现,人家可以设置)。我只能把树展开,变成单层数组。然后还要记录已经递归到第一层了。比如这样。

<!doctype html>

<html lang="en-US">

<head>

   <meta charset="UTF-8">

   <title></title>

</head>

<body>

<scripttype="text/javascript">

   var self = this;

   self.list =  [

       {

           "id": 1,

           "title": "node1",

           "children": [

                {

                    "id": 11,

                    "title":"node1.1",

                    "children": [

                        {

                            "id": 111,

                            "title":"node1.1.1"

                        }

                    ]

                },

                {

                    "id": 12,

                    "title":"node1.2",

                    "children": []

                }

           ]

       },

       {

           "id": 2,

           "title": "node2",

           "nodrop": true,

           "children": [

                {

                    "id": 21,

                    "title": "node2.1",

                    "children": []

                },

                {

                    "id": 22,

                    "title":"node2.2",

                    "children": []

                }

           ]

       },

       {

            "id": 3,

           "title": "node3",

           "children": [

                {

                    "id": 31,

                    "title":"node3.1",

                    "children": []

                }

           ]

       }

   ];

   function flatten (arr,level){

       var result = [],

                recursion = function(arr,level) {

                    arr.level = arr.level ||level || 0;

                    //这里用了个巧妙的方法,记录该数组的level。有就用它自己的,没有就判断是不是别人给它的,别人给的一般代表自己是子树。然后给的时候 +1

                    arr.forEach(function (item){

                        item.$$treeLevel =  arr.level;

                        result.push(item);

                        item.children&& recursion(item.children,arr.level + 1);

                    });

                    delete arr.level;

                };

       recursion(arr);

       return result;

   };

   self.arr = flatten(self.list);

   console.log(self.arr);

</script>

</body>

</html>

资料领取群598399936


本文由【waitig】发表在等英博客
本文固定链接:js展开一颗树
欢迎关注本站官方公众号,每日都有干货分享!
等英博客官方公众号
点赞 (0)分享 (0)