解析Javascript中的二维JSON数组 [英] Parse 2 dimensional JSON array in Javascript
问题描述
我有一个二维JSON数组,其中每个元素包含多个属性.下面的示例是有意简化的:
var map_data = { "1":
{"1":{"name":"aa"},"2":{"name":"bb"}},
"2":
{"1":{"name":"cc"},"2":{"name":"dd"}}
};
我尝试解析数据,但.length
不起作用:
for(x=1; x<=map_data.length; x++) {
for(y=1; y<=map_data[x].length; y++) {
// CODE
}
}
非常感谢!
那不是数组,它们是简单的对象,所以不能使用length
属性.
您需要使用 for...in
声明:
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
}
}
}
hasOwnProperty
检查是因为此语句遍历所有属性(无论是否继承),并且如果某些内容(例如某些JavaScript框架)增强了Array.prototype
或Object.prototype
对象,则这些增强的属性也将被迭代. /p>
您应该知道,该语句不能确保迭代的顺序.
我建议您使用真实"数组:
[
[{"name":"aa"},{"name":"bb"}],
[{"name":"cc"},{"name":"dd"}]
]
通过这种方式,您将能够使用length
属性来遍历索引.
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.
这篇关于解析Javascript中的二维JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!