Traverse all the Nodes of a JSON Object Tree with JavaScript

前端 未结 16 1776
猫巷女王i
猫巷女王i 2020-11-22 06:26

I\'d like to traverse a JSON object tree, but cannot find any library for that. It doesn\'t seem difficult but it feels like reinventing the wheel.

In XML there are

16条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 07:12

    If you think jQuery is kind of overkill for such a primitive task, you could do something like that:

    //your object
    var o = { 
        foo:"bar",
        arr:[1,2,3],
        subo: {
            foo2:"bar2"
        }
    };
    
    //called with every property and its value
    function process(key,value) {
        console.log(key + " : "+value);
    }
    
    function traverse(o,func) {
        for (var i in o) {
            func.apply(this,[i,o[i]]);  
            if (o[i] !== null && typeof(o[i])=="object") {
                //going one step down in the object tree!!
                traverse(o[i],func);
            }
        }
    }
    
    //that's all... no magic, no bloated framework
    traverse(o,process);
    

提交回复
热议问题