2011-05-05 124 views
1

我有一个数组嵌套在对象内部的对象也是在一个对象中。JSON数据检索

编辑:我的原始数据结构是畸形的,所以这里的console.log的屏幕盖(数据):

enter image description here

这正从一个AJAX请求返回,我遇到数组问题。诀窍是它不会总是每个父对象返回3个数组,数组的数量依赖于“length”,或者说,“length”是每个包含数组的对象期望有多少个数组的反映。 “OID”是“th”和“uh”对象的每个数组的名称。

还有恰巧是几个主要对象,在迭代与for(var i in data)

我已经试过类似:

for(var i in data) { 
    for(var x in data[i].clicks) { 
     //And now I'm lost here 
     //I've tried getting the name of the Array from "OID" 
     //and going from there, that failed miserably. 
    } 
} 

我怎样才能在每个这些阵列的内容,它如果这可以在不知道所述数组的名称,数量或长度的情况下完成,则是最好的。

在此先感谢。

回答

1

你的问题和数据结构不是很清楚,我不熟悉你用来声明数组的语法,这对我来说似乎是不正确的。

如果你打算你的数据结构是

data={ 
    "Clicks": { 
      "length": 3, //Can be between 0-3 
      "OID": { 
       1: "1", 
       2: "2", 
       3: "3" 
      }, 
      "th": { 
      1: [ 
       null, 
       null, 
       null, 
       null 
      ], 
      2: [ 
       null, 
       null, 
       null, 
       null 
      ], 
      3: [ 
       null, 
       null, 
       null, 
       null 
      ] 
      }, 
      "uh": { 
      1: [ 
       null, 
       null, 
       null, 
       null 
      ], 
      2: [ 
       null, 
       null, 
       null, 
       null 
      ], 
      3: [ 
       null, 
       null, 
       null, 
       null 
      ] 
     } 
    } 
}; 

和你想要做的是遍历所有元素thuh其中关键来自条目OID,你应该做的事情像

for(var i = 1; i <= data.Clicks.length; i++){ 
    data.Clicks.th[data.Clicks.OID[i]]; 
    data.Clicks.uh[data.Clicks.OID[i]]; 
} 

但是,如果你的钥匙都不会是什么,但数字,好像你可以通过返回一个数组的数组为每个thuh得到更好的服务:

data={ 
    "Clicks": { 
      "th": [ 
       [ 
        null, 
        null, 
        null, 
        null 
       ], 
       [ 
        null, 
        null, 
        null, 
        null 
       ], 
       [ 
        null, 
        null, 
        null, 
        null 
       ] 
      ], 
      "uh": [ 
       [ 
        null, 
        null, 
        null, 
        null 
       ], 
       [ 
        null, 
        null, 
        null, 
        null 
       ], 
       [ 
        null, 
        null, 
        null, 
        null 
       ] 
      ] 
     } 
    }; 

和访问它作为

//assuming th and uh are of the same length always 
for(var i = 1; i <= data.Clicks.th.length; i++){ 
    data.Clicks.th[i]; 
    data.Clicks.uh[i]; 
} 
+0

第一个建议伟大的工作。谢谢! – 2011-05-06 00:14:52