(@_@;)我是程序猿,我编程,我快乐,知识改变命运,技术成就梦想   oh yeah!合作VX "w6668263" 联系Email:ye583025823@126.com

如何用 js 递归输出树型

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>

    <script>

        var data = [
            { id: 1, title: 'a', pid: 0 },
            { id: 2, title: 'a1', pid: 1 },
            { id: 3, title: 'a11', pid: 2 },
            { id: 4, title: 'a12', pid: 2 },
            { id: 5, title: 'a2', pid: 1 },
            { id: 6, title: 'a21', pid: 5 }
        ];
        function fn(data, pid) {
            var result = [], temp;
            for (var i in data) {
                if (data[i].pid == pid) {
                    result.push(data[i]);
                    temp = fn(data, data[i].id);
                    if (temp.length > 0) {
                        data[i].children = temp;
                    }
                }
            }
            return result;
        }
        //console.log(fn(data, 0));


        Array.prototype.ToTreeJson = function (pid) {
            var result = [], temp;
            for (var i in this) {
                if (this[i].pid == pid) {
                    result.push(this[i]);
                    temp = fn(this, this[i].id);
                    if (temp.length > 0) {
                        this[i].children = temp;
                    }
                }
            }
            return result;
        }

        var p = data.ToTreeJson(0);
    </script>
</body>
</html>

 

posted on 2015-09-06 22:19  一个草率的龙果果  阅读(2624)  评论(0编辑  收藏  举报

导航