0xbadf00d 0xbadf00d - 1 month ago 22
Javascript Question

More efficient way to extract address components

Currenty, I'm using the following code to get the country, postal code, locality and sub-locality:

var country, postal_code, locality, sublocality;
for (i = 0; i < results[0].address_components.length; ++i)
{
for (j = 0; j < results[0].address_components[i].types.length; ++j)
{
if (!country && results[0].address_components[i].types[j] == "country")
country = results[0].address_components[i].long_name;
else if (!postal_code && results[0].address_components[i].types[j] == "postal_code")
postal_code = results[0].address_components[i].long_name;
else if (!locality && results[0].address_components[i].types[j] == "locality")
locality = results[0].address_components[i].long_name;
else if (!sublocality && results[0].address_components[i].types[j] == "sublocality")
sublocality = results[0].address_components[i].long_name;
}
}


That's unsatisfactory. Is there any other way to achieve the same result?

Answer
if (typeof Object.keys == 'function')
    var length = function(x) { return Object.keys(x).length; };
else
    var length = function() {};

var location = {};      
for (i = 0; i < results[0].address_components.length; ++i)
{
    var component = results[0].address_components[i];
    if (!location.country && component.types.indexOf("country") > -1)
        location.country = component.long_name;
    else if (!location.postal_code && component.types.indexOf("postal_code") > -1)
        location.postal_code = component.long_name;
    else if (location.locality && component.types.indexOf("locality") > -1)
        location.locality = component.long_name;
    else if (location.sublocality && component.types.indexOf("sublocality") > -1)
        location.sublocality = component.long_name;

    // nothing will happen here if `Object.keys` isn't supported!
    if (length(location) == 4)
        break;
}

This is the most suitable solution for me. It may help someone too.

Comments