如何用 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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM