Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have this below type of array. I want to iterate this array in JavaScript. How is this possible?

var dictionary = {
    "data":[
        {"id":"0","name":"ABC"},
        {"id":"1","name":"DEF"}
    ],
    "images": [
        {"id":"0","name":"PQR"},
        {"id":"1","name":"xyz"}
    ]
};
share|improve this question
whathaveyoutried? – creinig Mar 19 at 10:13
Maybe someone will finally create a webpage for OP's. I have tried nothing. – dfsq Mar 19 at 10:15

6 Answers

up vote 1 down vote accepted

You can do it with the below code. You first get the data array using dictionalry.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.

share|improve this answer
thanks for response......... – Android Mar 19 at 10:39
for(index in dictionary) {
 for(var index in dictionary[]){
    // do something
  }
}
share|improve this answer
thanks for response......... – Android Mar 19 at 10:39

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]);
  }
}
share|improve this answer
for(var foo in dictionary){
  for(var bar in dictionary[foo]){
    for(var baz in dictionary[foo][bar]){
      // do something...
      console.log(foo + ' > ' + baz + ' > ' + dictionary[foo][bar][baz]);
    }
  }
}

FYI: Arrays <-> Objects syntactically inter-changable in Javascript.

share|improve this answer

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.

share|improve this answer

There's this way too (new to EcmaScript5):

dictionary.data.forEach(function(item){
    console.log(item.name + ' ' + item.id);
});

Same approach for images

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.