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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With