javascript 樹形數據轉化維數組

javascript 樹形數據轉化維數組

廢話不多說直接上代碼。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>遍歷樹</title>
</head>
<body>


<script>
    window.onload = function () {
        var data = [
            {
                "id": 1,
                "text": "aa",
                "children": [
                    {"id": 2, "text": "bb"},
                    {"id": 3, "text": "cc"},
                    {"id": 4, "text": "dd"},
                    {"id": 5, "text": "ee"},
                    {
                        "id": 6, 
                        "text": "ff",
                        "children": [
                            {"id": 7, "text": "gg"},
                            {"id": 8, "text": "hh"},
                        ]
                    }
                ]
            },
            {
                "id": 10,
                "text": "aa0",
                "children": [
                    {"id": 20, "text": "bb0"},
                    {"id": 30, "text": "cc0"},
                    {"id": 40, "text": "dd0"},
                    {"id": 50, "text": "ee0"},
                    {
                        "id": 60, 
                        "text": "ff0",
                        "children": [
                            {"id": 70, "text": "gg0"},
                            {"id": 80, "text": "hh0"},
                        ]
                    }
                ]
            }
        ];

        console.log(convert_tree_data(data));

        function convert_tree_data(data) {
            for (var i = 0; i < data.length; i++) {
                if (data[i].children != undefined) {
                    var temp = data[i].children;
                    // 刪除孩子節點
                    delete data[i].children;
                    // 孩子節點加入數組末尾
                    for (var j = 0; j < temp.length; j++) {
                        data.push(temp[j]);
                    }
                }
            }

            return data;
        }
    }

</script>


</body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章