4

Possible Duplicate:
I have a nested data structure / JSON, how can access a specific value?

I want to iterate through a json object which is two dimensional ... for a one dimensional json object I do this

for (key in data) {
alert(data[key]);
}

what do i do about a two dimensional one??

6
  • 2
    Could you show us data ?
    – Adil
    Commented Nov 24, 2012 at 19:07
  • How to iterate through a json object? it would be easier having the data in front of my face
    – Ryan
    Commented Nov 24, 2012 at 19:08
  • see this stackoverflow.com/questions/2488148/…
    – Hapie
    Commented Nov 24, 2012 at 19:08
  • 2
    2 dimensional can mean numerous things... a little extra effort when posting questions would help. Also , doing a little searching would have likely given you your answer
    – charlietfl
    Commented Nov 24, 2012 at 19:08
  • if i alert(data) i get [object Object],[object Object] .... i get the desired output when i type alert(data[0][1])..but i want to alert all the elements ...
    – user1849908
    Commented Nov 24, 2012 at 19:15

3 Answers 3

16

There is no two dimensional data in Javascript, so what you have is nested objects, or a jagged array (array of arrays), or a combination (object with array properties, or array of objects). Just loop through the sub-items:

for (var key in data) {
  var item = data[key];
  for (var key2 in item) {
    alert(item[key2]);
  }
}
3
  • +1 not bad, caching item ;-) Commented Nov 24, 2012 at 19:18
  • it works but am getting the output twice ....
    – user1849908
    Commented Nov 24, 2012 at 19:34
  • i get data[0][1] then data[0][2] , data[0][3] then again i get data[0][1], data[0][2], data[0][3] ... then data[1][0] and so on ...
    – user1849908
    Commented Nov 24, 2012 at 19:36
2

perhaps you want

for(var i in data){
  for(var j in data[i]){
    alert(data[i][j]);
  }
}
1

Try:

for (var key in data) {
   for (var key2 in data[key]){
      alert(data[key][key2]);
   }
}