Brian Cray ··· Home > Blog > Javascript > Javascript snippet: Find the value of a string key in a multidimensional array or object

Javascript snippet: Find the value of a string key in a multidimensional array or object

While building Nearby Tweets v2 I had trouble grabbing the proper city/state/country name out of Google Maps API's Geocoding JSON object. The problem was that the JSON object is structured differently for different places across the world.

After multiple tweaks to pick the right information out of an unpredictable multidimensional structure, I finally decided to search the object for the keys I wanted and return their values. That way it wouldn't matter if the structure changed. But alas, I couldn't find a function that searches a multidimensional array or object for a string key and returns the value. So, I had to write my own.

Javascript source code

This modifies the String prototype to add the functionality we need. Using the string value of the object it runs on as the string key name, this function takes a multidimensional array or object as its parameter, and returns the first value it comes across (it does not continue to search).

// Use: stringvalue.findIn(multi_dimensional_array_or_object)
/***Example: 
    var tofind = 'emotion';
    var person = {'name': 'Bob Loblaw', 'age': '28', 'personality': {'smart': 'yes', 'funny': 'yes', 'emotion': 'happy'} };
    tofind.findIn(person) = 'happy'
***/

// The code that does it all:
String.prototype.findIn = function (multi) {
    multi = multi || '';
    var val = this.valueOf();
    if(typeof multi == 'object' || typeof multi == 'array')
    {
        if(val in multi)
        {
            return multi[val];
        }
        else
        {
            for(var x in multi)
            {
                var found = this.findIn(multi[x]);
                if(found != false)
                {
                    return found;
                }
            }
        }
    }
    return false;
};