Elankeeran
Elankeeran

Reputation: 6184

How to iterate json data in jquery

How to iterate the json data in jquery.

[{"id":"856","name":"India"},
 {"id":"1035","name":"Chennai"},
 {"id":"1048","name":"Delhi"},
 {"id":"1113","name":"Lucknow"},
 {"id":"1114","name":"Bangalore"},
 {"id":"1115","name":"Ahmedabad"},
 {"id":"1116","name":"Cochin"},
 {"id":"1117","name":"London"},
 {"id":"1118","name":"New York"},
 {"id":"1119","name":"California"}
]

Upvotes: 24

Views: 59150

Answers (4)

shayuna
shayuna

Reputation: 484

iterate on all the object's properties with the $.each function. in each iteration you'll get the name/key and the value of the property:

$.each(data, function(key, val) {
  alert(key+ " *** " + val);
});

Upvotes: 3

cambraca
cambraca

Reputation: 27827

You can just use regular javascript too, which I think would be a bit faster (though I'm not really sure how jQuery optimizes each):

var data = [{"id":"856","name":"India"},
 {"id":"1035","name":"Chennai"},
 {"id":"1048","name":"Delhi"},
 {"id":"1113","name":"Lucknow"},
 {"id":"1114","name":"Bangalore"},
 {"id":"1115","name":"Ahmedabad"},
 {"id":"1116","name":"Cochin"},
 {"id":"1117","name":"London"},
 {"id":"1118","name":"New York"},
 {"id":"1119","name":"California"}
];

var data_length = data.length;
for (var i = 0; i < data_length; i++) {
  alert(data[i]["id"] + " " + data[i]["name"]);
}

edited to reflect Nick's suggestion about performance

Upvotes: 7

Nick Craver
Nick Craver

Reputation: 630597

You can use $.each() like this:

$.each(data, function(i, obj) {
  //use obj.id and obj.name here, for example:
  alert(obj.name);
});

Upvotes: 56

Darin Dimitrov
Darin Dimitrov

Reputation: 1039418

You could use the .each() function:

$(yourjsondata).each(function(index, element) {
    alert('id: ' + element.id + ', name: ' + element.name);
});

Upvotes: 3

Related Questions