Traverse all the Nodes of a JSON Object Tree with JavaScript

前端 未结 16 1773
猫巷女王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 06:56

    Most Javascript engines do not optimize tail recursion (this might not be an issue if your JSON isn't deeply nested), but I usually err on the side of caution and do iteration instead, e.g.

    function traverse(o, fn) {
        const stack = [o]
    
        while (stack.length) {
            const obj = stack.shift()
    
            Object.keys(obj).forEach((key) => {
                fn(key, obj[key], obj)
                if (obj[key] instanceof Object) {
                    stack.unshift(obj[key])
                    return
                }
            })
        }
    }
    
    const o = {
        name: 'Max',
        legal: false,
        other: {
            name: 'Maxwell',
            nested: {
                legal: true
            }
        }
    }
    
    const fx = (key, value, obj) => console.log(key, value)
    traverse(o, fx)
    

提交回复
热议问题