Traverse all the Nodes of a JSON Object Tree with JavaScript

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

    var test = {
        depth00: {
            depth10: 'string'
            , depth11: 11
            , depth12: {
                depth20:'string'
                , depth21:21
            }
            , depth13: [
                {
                    depth22:'2201'
                    , depth23:'2301'
                }
                , {
                    depth22:'2202'
                    , depth23:'2302'
                }
            ]
        }
        ,depth01: {
            depth10: 'string'
            , depth11: 11
            , depth12: {
                depth20:'string'
                , depth21:21
            }
            , depth13: [
                {
                    depth22:'2201'
                    , depth23:'2301'
                }
                , {
                    depth22:'2202'
                    , depth23:'2302'
                }
            ]
        }
        , depth02: 'string'
        , dpeth03: 3
    };
    
    
    function traverse(result, obj, preKey) {
        if(!obj) return [];
        if (typeof obj == 'object') {
            for(var key in obj) {
                traverse(result, obj[key], (preKey || '') + (preKey ? '[' +  key + ']' : key))
            }
        } else {
            result.push({
                key: (preKey || '')
                , val: obj
            });
        }
        return result;
    }
    
    document.getElementById('textarea').value = JSON.stringify(traverse([], test), null, 2);

提交回复
热议问题