How to iterate object in JavaScript?
Something like that:
var dictionary = {"data":[{"id":"0","name":"ABC"},{"id":"1", "name":"DEF"}], "images": [{"id":"0","name":"PQR"},{"id":"1","name":"xyz"}]};
for (item in dictionary) {
for (subItem in dictionary[item]) {
console.log(dictionary[item][subItem].id);
console.log(dictionary[item][subItem].name);
}
}
You can do it with the below code. You first get the data array using dictionary.data and assign it to the data variable. After that you can iterate it using a normal for loop. Each row will be a row object in the array.
var data = dictionary.data;
for (var i in data)
{
var id = data[i].id;
var name = data[i].name;
}
You can follow similar approach to iterate the image array.
There's this way too (new to EcmaScript5):
dictionary.data.forEach(function(item){
console.log(item.name + ' ' + item.id);
});
Same approach for images
Use dot notation and/or bracket notation to access object properties and for
loops to iterate arrays:
var d, i;
for (i = 0; i < dictionary.data.length; i++) {
d = dictionary.data[i];
alert(d.id + ' ' + d.name);
}
You can also iterate arrays using for
..in
loops; however, properties added to Array.prototype
may show through, and you may not necessarily get array elements in their correct order, or even in any consistent order.