Traverse all the Nodes of a JSON Object Tree with JavaScript

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

    Depends on what you want to do. Here's an example of traversing a JavaScript object tree, printing keys and values as it goes:

    function js_traverse(o) {
        var type = typeof o 
        if (type == "object") {
            for (var key in o) {
                print("key: ", key)
                js_traverse(o[key])
            }
        } else {
            print(o)
        }
    }
    
    js> foobar = {foo: "bar", baz: "quux", zot: [1, 2, 3, {some: "hash"}]}
    [object Object]
    js> js_traverse(foobar)                 
    key:  foo
    bar
    key:  baz
    quux
    key:  zot
    key:  0
    1
    key:  1
    2
    key:  2
    3
    key:  3
    key:  some
    hash
    
    0 讨论(0)
  • 2020-11-22 07:18

    My Script:

    op_needed = [];
    callback_func = function(val) {
      var i, j, len;
      results = [];
      for (j = 0, len = val.length; j < len; j++) {
        i = val[j];
        if (i['children'].length !== 0) {
          call_func(i['children']);
        } else {
          op_needed.push(i['rel_path']);
        }
      }
      return op_needed;
    };
    

    Input JSON:

    [
        {
            "id": null, 
            "name": "output",   
            "asset_type_assoc": [], 
            "rel_path": "output",
            "children": [
                {
                    "id": null, 
                    "name": "output",   
                    "asset_type_assoc": [], 
                    "rel_path": "output/f1",
                    "children": [
                        {
                            "id": null, 
                            "name": "v#",
                            "asset_type_assoc": [], 
                            "rel_path": "output/f1/ver",
                            "children": []
                        }
                    ]
                }
           ]
       }
    ]
    

    Function Call:

    callback_func(inp_json);
    

    Output as per my Need:

    ["output/f1/ver"]
    
    0 讨论(0)
  • 2020-11-22 07:19

    We use object-scan for all our data processing needs now. It's very powerful once you wrap your head around it. Here is how you could do basic traversal

    const objectScan = require('object-scan');
    
    const obj = {
      foo: 'bar',
      arr: [1, 2, 3],
      subo: {
        foo2: 'bar2'
      }
    };
    
    objectScan(['**'], {
      filterFn: ({ key, value }) => {
        console.log(key, value);
      }
    })(obj);
    /* =>
    [ 'subo', 'foo2' ] 'bar2'
    [ 'subo' ] { foo2: 'bar2' }
    [ 'arr', 2 ] 3
    [ 'arr', 1 ] 2
    [ 'arr', 0 ] 1
    [ 'arr' ] [ 1, 2, 3 ]
    [ 'foo' ] 'bar'
    */
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
提交回复
热议问题