Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse 2 dimensional JSON array in Javascript

I have a two dimensional JSON array where each element contains several attributes. The example below is intentionally simplified:

var map_data = { "1":
                      {"1":{"name":"aa"},"2":{"name":"bb"}},
                 "2":
                      {"1":{"name":"cc"},"2":{"name":"dd"}}
               };

I try to parse the data but .length doesn't work:

for(x=1; x<=map_data.length; x++) { 
    for(y=1; y<=map_data[x].length; y++) {
        // CODE 
    }
}

Many, many thanks!

like image 844
MrG Avatar asked Dec 18 '22 02:12

MrG


1 Answers

That's not an array, they are simple objects, that's why you cannot use the length property.

You need to use the for...in statement:

for(var x in map_data) { 
  if (map_data.hasOwnProperty(x))
    for(var y in map_data[x]) {
      if (map_data[x].hasOwnProperty(y)) {
        // CODE
      }
    }
}

The hasOwnProperty checks are because this statement iterates over all properties, inherited or not, and if something (like some JavaScript frameworks) augmented the Array.prototype or Object.prototype objects, those augmented properties will be also iterated.

You should know that this statement doesn't ensure anyhow the order of iteration.

I would recommend you to use a "real" array:

[
 [{"name":"aa"},{"name":"bb"}],
 [{"name":"cc"},{"name":"dd"}]
]

In this way you will be able to use the length property to iterate over the indexes.

like image 91
Christian C. Salvadó Avatar answered Jan 08 '23 14:01

Christian C. Salvadó