Traverse all the Nodes of a JSON Object Tree with JavaScript

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

    There's a new library for traversing JSON data with JavaScript that supports many different use cases.

    https://npmjs.org/package/traverse

    https://github.com/substack/js-traverse

    It works with all kinds of JavaScript objects. It even detects cycles.

    It provides the path of each node, too.

    0 讨论(0)
  • 2020-11-22 07:05

    I've created library to traverse and edit deep nested JS objects. Check out API here: https://github.com/dominik791

    You can also play with the library interactively using demo app: https://dominik791.github.io/obj-traverse-demo/

    Examples of usage: You should always have root object which is the first parameter of each method:

    var rootObj = {
      name: 'rootObject',
      children: [
        {
          'name': 'child1',
           children: [ ... ]
        },
        {
           'name': 'child2',
           children: [ ... ]
        }
      ]
    };
    

    The second parameter is always the name of property that holds nested objects. In above case it would be 'children'.

    The third parameter is an object that you use to find object/objects that you want to find/modify/delete. For example if you're looking for object with id equal to 1, then you will pass { id: 1} as the third parameter.

    And you can:

    1. findFirst(rootObj, 'children', { id: 1 }) to find first object with id === 1
    2. findAll(rootObj, 'children', { id: 1 }) to find all objects with id === 1
    3. findAndDeleteFirst(rootObj, 'children', { id: 1 }) to delete first matching object
    4. findAndDeleteAll(rootObj, 'children', { id: 1 }) to delete all matching objects

    replacementObj is used as the last parameter in two last methods:

    1. findAndModifyFirst(rootObj, 'children', { id: 1 }, { id: 2, name: 'newObj'}) to change first found object with id === 1 to the { id: 2, name: 'newObj'}
    2. findAndModifyAll(rootObj, 'children', { id: 1 }, { id: 2, name: 'newObj'}) to change all objects with id === 1 to the { id: 2, name: 'newObj'}
    0 讨论(0)
  • 2020-11-22 07:05

    The best solution for me was the following:

    simple and without using any framework

        var doSomethingForAll = function (arg) {
           if (arg != undefined && arg.length > 0) {
                arg.map(function (item) {
                      // do something for item
                      doSomethingForAll (item.subitem)
                 });
            }
         }
    
    0 讨论(0)
  • 2020-11-22 07:05
                 var localdata = [{''}]// Your json array
                  for (var j = 0; j < localdata.length; j++) 
                   {$(localdata).each(function(index,item)
                    {
                     $('#tbl').append('<tr><td>' + item.FirstName +'</td></tr>);
                     }
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 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)

    0 讨论(0)
提交回复
热议问题