user4741577
user4741577

Reputation:

How do i iterate through JSON array in javascript?

I have a json data coming from rest in following format:

{
"status_code": 200, 
"data": {
"units": -1, 
"unit_reference_ts": null,
"tz_offset": -4,
"unit": "day", 
"countries": [{"country": "IN", "clicks": 12}]}, 
"status_txt": "OK"
}

I want to access the countries part and need to generate data in format like

{"IN":12, ......}

I dont know how to iterate through javascript, JSON array? Please help i am confused between methods which is the best & easiest that will work throughout the JSON?

I tried this:

 $.each(response.countries, function(key, value) {
 console.log(value.country + ": " + value.clicks);});

but it is showing me type error e is undefined...

Upvotes: 1

Views: 55

Answers (1)

Andy
Andy

Reputation: 63524

Make sure you parse your JSON first (var data = JSON.parse(json)), then use a simple loop:

var obj = {};
for (var i = 0, l = data.data.countries.length; i < l; i++) {
    var tmp = data.data.countries[i];
    obj[tmp.country] = tmp.clicks
}

console.log(obj); // { IN: 12, UK: 123 }

DEMO

Since (from your edit) you're using jQuery, you'll probably need to do this (note that jQuery automatically parses JSON data if you retrieve it using one of its AJAX methods):

var obj = {};
$.each(response.data.countries, function(key, value) {
    obj[value.country] = value.clicks;
});

If you want a string instead of an object, just JSON.stringify the obj:

var json = JSON.stringify(obj);

DEMO

Upvotes: 2

Related Questions