Skip to content Skip to sidebar Skip to footer

Json Result Get Country From Address_components

Hi new to JSON and I was wondering if I can call the 'country' from this API's JSON result: http://maps.google.com/maps/api/js?sensor=true&libraries=places I tried to use a lo

Solution 1:

in your case you will have to manually iterate the array and check that the types array contains 'country'. You can use array.indexof for this.

for(var row=0; row<data.results.length;row++){
    var item = data.results[row];
    for( var i = 0; i< item.address_components.length; i++) {
         var component = item.address_components[i];
         if( component.types.indexof('country') != -1) {
             document.getElementById('res').value = component.long_name;
          }
    }
}

Solution 2:

A more updated answer using ES6

data.results[0].address_components.forEach(_item => {
  if (_item.types.indexOf('country') !== -1) {
     document.getElementById('res').value = _item.short_name;
  }
});

Post a Comment for "Json Result Get Country From Address_components"