使用javascript循环读取json数字数组

时间:2017-07-20 19:07:08

标签: javascript arrays json sorting date

我正在尝试编写一个将通过嵌套数字数组读取的循环。

我读的Json文件是这样的。每个数字键代表事件日期。 json reference for startdate and end date enter image description here

我有以下javascript,每个var i = 1或j = 1。 我想从日期中读取整个嵌套数字并将它们存储在某个地方。

$(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看起来不像是一个数组,我似乎无法将其读作数字列表来阅读。非常感谢帮助。

如果有人甚至可以排除离今天爱因斯坦最近的距离最远的那个:)

2 个答案:

答案 0 :(得分:1)

您将成为一个对象数组,其中包含一个callEvent对象,该对象具有dates属性,该属性是一个包含属性startDateTime和endDateTime的对象的数组。 它将如下所示:

[
    {
      callEvent: {
        dates: [
          {startDateTime: '', endDateTime: ''},
          // more objects with start- and endDateTime
        ]
      }
    },
    // more callEvent objects..
]

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

$(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)
            }
        }

    });
});

答案 1 :(得分:0)

假设日期是有效的JSON(JSON Validator),那么你应该能够获取数据并循环遍历它:

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