Iterate through nested JSON Data using javascript

By
Advertisement
Below is the code used:

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <meta charset="utf-8" />
    <title>JS Bin</title>
</head>
<body>
    <div id="output">
    </div>
    <script>
        (function () {
            var myobj = {
                obj1: { key1: 'val1', key2: 'val2' },
                obj2: { key1: '2val1',
                    key2: { nest1: 'val1', nest2: 'val2', nest3: 'val3' },
                    key3: { nest1: 'K3val1', nest2: 'K3val2',
                        nest3: [
                        { nest1: 'val1', nest2: 'val2', nest3: 'val3' },
                        { nest1: 'val1', nest2: 'val2', nest3: 'val3' }
                      ]
                    }
                },
                obj3: { key1: 'dddddval1', key2: 'val2' }
            };

            // Loop the top level
            $.each(myobj, walker);

            function walker(key, value) {
                // ...do what you like with `key` and `value`


                if (typeof value === "object") {
                    // Recurse into children
                    $.each(value, walker);
                }
                else {
                    display(key + " : " + value + "<br/>");
                }
            }

            function display(msg) {
                //var p = document.createElement('p');
                //p.innerHTML = String(msg);
                $('#output').append(msg);
            }
        })();
   
   
    </script>
</body>
</html>


 Output:

key1 : val1
key2 : val2
key1 : 2val1
nest1 : val1
nest2 : val2
nest3 : val3
nest1 : K3val1
nest2 : K3val2
nest1 : val1
nest2 : val2
nest3 : val3
nest1 : val1
nest2 : val2
nest3 : val3
key1 : dddddval1
key2 : val2


0 comments:

Post a Comment

Online Casino