解析Javascript中的二维JSON数组 [英] Parse 2 dimensional JSON array in Javascript

查看:71
本文介绍了解析Javascript中的二维JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二维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.prototypeObject.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆