Traverse all the Nodes of a JSON Object Tree with JavaScript

前端 未结 16 1388
猫巷女王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:20

    I wanted to use the perfect solution of @TheHippo in an anonymous function, without use of process and trigger functions. The following worked for me, sharing for novice programmers like myself.

    (function traverse(o) {
        for (var i in o) {
            console.log('key : ' + i + ', value: ' + o[i]);
    
            if (o[i] !== null && typeof(o[i])=="object") {
                //going on step down in the object tree!!
                traverse(o[i]);
            }
        }
      })
      (json);
    

提交回复
热议问题