简体   繁体   中英

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...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM