Javascript遍历许多对象的对象

时间:2018-09-27 11:20:28

标签: javascript json

我有一个字符串JSON http响应。

{
    "1537988400000": {
        "6495": ["18", "29"],
        "6490": ["34", "40"],
        "6500": ["7", "213"],
        "6505": ["13", "17"]
    },
    "1537992000000": {
        "6490": ["45", "87"],
        "6485": ["15", "4"],
        "6495": ["78", "222"],
        "6500": ["176", "141"],
        "6505": ["64", "94"],
        "6510": ["7", "53"],
        "6515": ["0", "1"]
    }
}

我想将其解析为JavaScript对象。必须对对象进行结构化,以便我可以从数组中获取数字。例如,我选择"1537992000000" -> "6495" -> [1]并得到'222'。

这是我的代码:

var resp = this.responseText; // JSON string

var object = JSON.parse(resp);

for (var obj in object) {
    for (var a in obj) {
        alert(a[0]); // should return the first number in the array of an object
    }
}

问题在于它不返回数字。它发送类似01 .. 910 ..(似乎这些是每个属性的属性的索引)

3 个答案:

答案 0 :(得分:0)

for(var a in obj){ 
     

似乎这些是每个属性的属性的索引

是的。 That is what in does。使用of to loop over values

答案 1 :(得分:0)

您的JSON插入逻辑很好,您在这里误解了,obj是关键

for (var obj in object)

  

必须对对象进行结构化,以便可以从数组中获取数字。

var json={"1537988400000":{"6495":["18","29"],"6490":["34","40"],"6500":["7","213"],"6505":["13","17"]},"1537992000000":{"6490":["45","87"],"6485":["15","4"],"6495":["78","222"],"6500":["176","141"],"6505":["64","94"],"6510":["7","53"],"6515":["0","1"]}}

for(var i in json){
  for(var j in json[i]){
    console.log(json[i][j]);
  }
}

答案 2 :(得分:0)

var data = '{"1537988400000":{"6495":["18","29"],"6490":["34","40"],"6500":["7","213"],"6505":["13","17"]},"1537992000000":{"6490":["45","87"],"6485":["15","4"],"6495":["78","222"],"6500":["176","141"],"6505":["64","94"],"6510":["7","53"],"6515":["0","1"]}}';

data = JSON.parse(data);



for (var obj in data) {

    for (var a in data[obj]) {
        console.log(data[obj][a]); 
    }
}