jQuery - How to recursively loop over an object's nested properties?

后端 未结 5 1270
执笔经年
执笔经年 2020-12-16 20:46

Is there are a way to recursively loop over all the nested properties of a JS/jQuery object?

For example, given this object

var x = {
    \'name\': \         


        
5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-16 21:01

    var x = {
        'name': 'a',
        'level': 1,
        'children': [{
            'name': 'b',
            'level' : 2,
            'children' : [{
                'name': 'c',
                'level' : 3,
                'children' : [{
                }]
            }]
        }, {
            'name': 'b2',
            'level' : 2,
            'children' : [{
                'name': 'c2',
                'level' : 3,
                'children' : [{
                }]
            }]
        }]
    }
    var step = x;
    do {
        if (step instanceof Array){
            for (i=0; i < step.length; i++) {
                callback(step[i]);
            }
        }
        else {
            callback(step);
        }
        step = step.children != undefined ? step.children : null;
    } while (step);
    
    function callback (element) {
        console.log(element);
    }
    

    as long as the structure does not change, you can go down like this.

提交回复
热议问题