使用javascript循环读取json数组

read through json number array using javascript loop

本问题已经有最佳答案,请猛点这里访问。

我正在写一个循环,它将读取嵌套的数字数组。

我正在读的JSON文件是这样的。每个数字键代表事件日期。开始日期和结束日期的JSON参考在此处输入图像描述

我在下面的javascript中读取每个var i=1或j=1。我想通读日期的整个嵌套编号,并将它们存储在某个地方。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
$(document).ready(function () {
  $.getJSON('http://app.toronto.ca/cc_sr_v1_app/data/edc_eventcal_APR?limit=500', function (data) {
    var data = data;
    var i = 2;
    var obj = data[i].calEvent;  
    var bingname = obj.eventName;
    var j = 1;
    var startdate = obj.dates[j].startDateTime;
    var time = new Date(startdate);
    var starttime = time.getFullYear()+'-' + (time.getMonth()+1) + '-'+time.getDate();
    var name = JSON.stringify(bingname);  

    document.getElementById("bingname").innerHTML = name;


    document.getElementById("bingtime").innerHTML = starttime;


    var name = firebase.database().ref("/bing").set({
      EventName : name,
      EventStart : starttime
    });

  });
});

现在,我应该对var j使用一些增量循环,但我不确定如何使用。对我来说,问题在于obj.dates[j]中检索到的json不像数组,我似乎无法将其作为要读取的数字列表来读取。非常感谢您的帮助。

如果有人能从今天的日期算起,把这个最接近最远的排序,那就是爱因斯坦。


您将成为一个对象数组,其中包括一个callevent对象,该对象具有dates属性,该属性是一个数组,其中包含具有startdatetime和enddatetime属性的对象。如下所示:

1
2
3
4
5
6
7
8
9
10
11
[
    {
      callEvent: {
        dates: [
          {startDateTime: '', endDateTime: ''},
          // more objects with start- and endDateTime
        ]
      }
    },
    // more callEvent objects..
]

现在,您的代码应该遍历数组以获取所有CallEvent对象,并遍历每个CallEvent中的所有日期对象。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$(document).ready(function () {
    $.getJSON('http://app.toronto.ca/cc_sr_v1_app/data/edc_eventcal_APR?limit=500', function (array) {

        // loop through all elements in the array
        for (var i = 0; i < array.length; i++) {
            // loop through all dates inside the array
            for (var j = 0; j < array[i].calEvent.dates.length; j++) {
                console.log(array[i].callEvent.dates[j].startDateTime)
                console.log(array[i].callEvent.dates[j].endDateTime)
            }
        }

    });
});


假设日期是有效的JSON(JSON验证器),那么您应该能够获取数据并通过它进行循环:

1
2
3
4
for (var i=0;i<data.length;++i) {
  console.log(data[i].startDateTime);
  console.log(data[i].endDateTime);
}