Traverse all the Nodes of a JSON Object Tree with JavaScript

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

    If you're traversing an actual JSON string then you can use a reviver function.

    function traverse (json, callback) {
      JSON.parse(json, function (key, value) {
        if (key !== '') {
          callback.call(this, key, value)
        }
        return value
      })
    }
    
    traverse('{"a":{"b":{"c":{"d":1}},"e":{"f":2}}}', function (key, value) {
      console.log(arguments)
    })
    

    When traversing an object:

    function traverse (obj, callback, trail) {
      trail = trail || []
    
      Object.keys(obj).forEach(function (key) {
        var value = obj[key]
    
        if (Object.getPrototypeOf(value) === Object.prototype) {
          traverse(value, callback, trail.concat(key))
        } else {
          callback.call(obj, key, value, trail)
        }
      })
    }
    
    traverse({a: {b: {c: {d: 1}}, e: {f: 2}}}, function (key, value, trail) {
      console.log(arguments)
    })
    

提交回复
热议问题