Traverse all the Nodes of a JSON Object Tree with JavaScript

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

    You can get all keys / values and preserve the hierarchy with this

    // get keys of an object or array
    function getkeys(z){
      var out=[]; 
      for(var i in z){out.push(i)};
      return out;
    }
    
    // print all inside an object
    function allInternalObjs(data, name) {
      name = name || 'data';
      return getkeys(data).reduce(function(olist, k){
        var v = data[k];
        if(typeof v === 'object') { olist.push.apply(olist, allInternalObjs(v, name + '.' + k)); }
        else { olist.push(name + '.' + k + ' = ' + v); }
        return olist;
      }, []);
    }
    
    // run with this
    allInternalObjs({'a':[{'b':'c'},{'d':{'e':5}}],'f':{'g':'h'}}, 'ob')
    

    This is a modification on (https://stackoverflow.com/a/25063574/1484447)

提交回复
热议问题