h1m4l
h1m4l

Reputation: 189

Traverse JSON data when index is in different array

I have a JSON obj as

var myJsonObj = {
                'key1' : {
                    'type' : 'key1 type',
                    'key1-1' : {
                        'type' : 'key1-1 type',
                        'data' : 'key1-1 value'
                    },
                    'key1-2' : {
                        'type' : 'key1-2 type',
                        'data' : 'key1-2 value'
                    },
                    'key1-3' : {
                        'type' : 'key1-3 type',
                        'key1-3-1' : {
                            'type' : 'key1-3-1 type',
                            'data' : 'key1-3-1 value'
                        },
                        'key1-3-2' : {
                            'type' : 'key1-3-2 type',
                            'data' : 'key1-3-1 value'
                        },
                        'key1-3-3': {
                            'type' : 'key1-3-3 type',
                            'key1-3-3-1' : {
                                'type' : 'key1-3-3-1 type',
                                'data' : 'key1-3-3-1 value'
                            },
                            'key1-3-3-2' : {
                                'type' : 'key1-3-3-2 type',
                                'data' : 'key1-3-3-2 value'
                            }
                        }
                    }
                }
            };

I have an array of index:

var index = new Array('key1', 'key1-3', 'key1-3-3');

How do I get the data from myJsonObj when indexs are known in index variable ? I want to fetch the result of myJsonObj['key1']['key1-3']['key1-3-3']. How to achieve the output ?

Upvotes: 0

Views: 145

Answers (1)

nnnnnn
nnnnnn

Reputation: 150080

You can do it with:

myJsonObj[ index[0] ][ index[1] ][ index[2] ]

Or if you want to allow for a variable number of levels in index:

var tmpObj = myJsonObj;
for (var i = 0; i < index.length; i++)
   tmpObj = tmpObj[index[i]];

Note that best practice on initialising an array with known values is to use the square bracket syntax:

var index = ['key1', 'key1-3', 'key1-3-3'];

And also there's no such thing as a JSON object.

Upvotes: 2

Related Questions