Traverse Through JSON object to find a value for a key

Finding value assigned to a JSON key is often used in lot of applications. This ready to use code snippet will help you to traverse through JSON object and find value for a key. In case there is no key found it will return null.


function lookupJson(obj, key) {
    var type = typeof key;
    if (type === 'string' || type === 'number') {
            key = ('' + key).replace(/\[(.*?)\]/, function (m, key) {
                return '.' + key;
            }).split('.');
    }
    //split the key using "."
    for (var i = 0, l = key.length; i < l; i++) {
        // If object found the key trim the object to the level and move on until the value is found
        if (obj.hasOwnProperty(key[i])) {
            obj = obj[key[i]];
        } else {
            return null;
        }
    }
    return obj;
}

Hope this code snippet helps you.

Advertisements

One thought on “Traverse Through JSON object to find a value for a key

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s