Traverse all the Nodes of a JSON Object Tree with JavaScript

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

    A JSON object is simply a Javascript object. That's actually what JSON stands for: JavaScript Object Notation. So you'd traverse a JSON object however you'd choose to "traverse" a Javascript object in general.

    In ES2017 you would do:

    Object.entries(jsonObj).forEach(([key, value]) => {
        // do something with key and val
    });
    

    You can always write a function to recursively descend into the object:

    function traverse(jsonObj) {
        if( jsonObj !== null && typeof jsonObj == "object" ) {
            Object.entries(jsonObj).forEach(([key, value]) => {
                // key is either an array index or object key
                traverse(value);
            });
        }
        else {
            // jsonObj is a number or string
        }
    }
    

    This should be a good starting point. I highly recommend using modern javascript methods for such things, since they make writing such code much easier.

提交回复
热议问题