Mr. Fox Mr. Fox - 4 months ago 8x
JSON Question

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:

I tried to use a loop that gets the last part of the JSON result address_components but I realized that the location of the "country" varies from the user's input

To elaborate:

Scenario 1:

736 Lockhart Court, Harristown QLD 4350, Australia


Australia //this is correct

Scenario 2:

Langley Air Force Base, Hampton, VA, United States


Virginia //not correct

My current code gets the last index of the array address_components and I am wondering if I can just do something like this *data.results[0].address_components[country].long_name;*, but I just don't know the proper way.


<script type="text/javascript" src=""></script>
<script src=""></script>
<script type="text/javascript">
$(document).ready(function() {
$("#btn1 ").click(function() {
var address=encodeURI($('#userInput').val());
var url=''+address+'&sensor=true';
$.getJSON(url, function(data){
for(var row=0; row<data.results.length;row++){
document.getElementById('res').value = (data.results[row].address_components[data.results[row].address_components.length-2].long_name);

<input type="text" id="res">
<input type="text" name="userInput" id="userInput" />

<input type="button" id="btn1" value="Load Data" />

How can I get a specific(country,street number etc) element without relying on the address_components index?


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;