Traverse all the Nodes of a JSON Object Tree with JavaScript

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

提交回复
热议问题