遞歸遍歷樹形json


前置知識:

1.首先 js里面“萬物皆對象”

2.遞歸:自己調用自己(遞歸的優缺點:https://www.cnblogs.com/tchjs/p/4428153.html  https://www.cnblogs.com/tchjs/p/4428153.html

我要遍歷一個樹形的array或者對象

1.對象

var json = {
            xiaomi:1,
            xiaohong:2,
            teamOne:{
                xiaoli:3,
                xiaohua:3
            },
            teamTwo:{
                xiaoyong:4
            }
        }

2.數組里對象數組

 var array = [{
                id: 1,
                children: [{
                    id: 2,
                    children: []
                }]
            },
            {
                id: 3,
                children: []
            },
            {
                id: 4,
                children: [{
                    id: 5,
                    children: [{
                            id: 6,
                            children: []
                        },

                        {
                            id: 7,
                            children: []
                        }
                    ]
                }]
            }
        ]

非常簡單一種遍歷方式:

function parseJson(jsonObj,id) {
            // 循環所有鍵
            for(var v in jsonObj){
                var element = jsonObj[v]
                // 1.判斷是對象或者數組
                if( typeof(element) == 'object'){
                    parseJson(element,id)
                }else{
                    if(element == id){
                        console.log(v+':'+id)
                    }
                }
            }
        }

調用:

parseJson(array,7) //id:7
parseJson(json,3) // xiaoli:3 xiaohua:3

 


免責聲明!

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



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