Diego Rodriguez
Diego Rodriguez

Reputation: 65

jQuery iterate over JSON arrays inside an object

I have the following JSON file:

{
    "Alaska": [{
        "countryName":"Alaska",
        "Phone”:”123”,
        "Rate”:”2¢/min"
    }],

    "Argentina": [{
        "countryName":"Argentina",
        "Phone”:”456”,
        "Rate”:”4¢/min"
    }],

    "Australia": [{
        "countryName":"Australia",
        "Phone”:”789”,
        "Rate”:”6¢/min
    }]
}

And I'm loading it and storing it in a variable like so:

var jsonOutput = {};

$.ajax({
    url: “countries.json",
    dataType: 'json',
    success: function(data) {
        jsonOutput = data;
    }
});

How can I iterate over it, using jQuery's .each similar to this?:

$(jsonOutput).each(function() {
    var output = this.countryName + this.Phone + this.Rate;
    console.log(output);
});

I have searched through tons of examples here but I couldn't find anything quite like this - most have all the arrays inside a parent object, and use the object.key format to read the data, but in my case it's returning 'undefined'.

Upvotes: 1

Views: 52

Answers (1)

Dhiraj
Dhiraj

Reputation: 33618

It should be something like below

$.each(jsonOutput, function(key, value) {
    var output = key + value[0].Phone + value[0].Rate;
    console.log(output);
});

jquery each

var jsonOutput = JSON.parse('{\
    "Alaska": [{\
        "countryName":"Alaska",\
        "Phone":"123",\
        "Rate":"2¢/min"\
    }],\
\
    "Argentina": [{\
        "countryName":"Argentina",\
        "Phone":"456",\
        "Rate":"4¢/min"\
    }],\
\
    "Australia": [{\
        "countryName":"Australia",\
        "Phone":"789",\
        "Rate":"6¢/min"\
    }]\
}');
$.each(jsonOutput, function(key, value) {
    var output = key + value[0].Phone + value[0].Rate;
    console.log(output);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

Related Questions