递归遍历树形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
原文地址:https://www.cnblogs.com/likewpp/p/10822128.html