I am trying to choose an element in an array based on one of it’s children’s values.
Using the results returned from the Google Maps API geocode request as an example, we have an array of the form:
{
"address_components": [
{
"long_name": "Renshaw St",
"short_name": "Renshaw St",
"types": [
"route"
]
},
{
"long_name": "Eccles",
"short_name": "Eccles",
"types": [
"locality",
"political"
]
},
{
"long_name": "Greater Manchester",
"short_name": "Gt Man",
"types": [
"administrative_area_level_2",
"political"
]
},
{
"long_name": "United Kingdom",
"short_name": "GB",
"types": [
"country",
"political"
]
},
{
"long_name": "M30 0PQ",
"short_name": "M30 0PQ",
"types": [
"postal_code"
]
},
{
"long_name": "Manchester",
"short_name": "Manchester",
"types": [
"postal_town"
]
}
],
"formatted_address": "Renshaw St, Eccles, Manchester, Greater Manchester M30 0PQ, UK",
"geometry": {
"bounds": {
"northeast": {
"lat": 53.48266090000001,
"lng": -2.35206530
},
"southwest": {
"lat": 53.48128999999999,
"lng": -2.35324410
}
},
"location": {
"lat": 53.4822450,
"lng": -2.35294730
},
"location_type": "GEOMETRIC_CENTER",
"viewport": {
"northeast": {
"lat": 53.48332443029150,
"lng": -2.351305719708498
},
"southwest": {
"lat": 53.48062646970850,
"lng": -2.354003680291502
}
}
},
"types": [
"route"
]
}
I’d like to choose the address_component->long_name that has the element type equal to a value I specify.
I have written the following code that takes the above array and a key to find as parameters and seems to work well:
function getAddressComponent(key, result) {
var rtn;
$.each(result,function(index,value){
if( result[index].types[0] == key ) rtn = result[index].long_name;
});
return rtn;
}
But was wondering if anyone could suggest a better approach as I have seen it done a few different ways and would like to use the optimal one.
Your code isn’t that long.. lol. You can return the result immediately because once you found it, you can leave the loop. And I didn’t investige the jQuery forEach but it couldn’t be shorter than the code below, I reckon.
How is this?