1

I have a function, which gets a Date and is reading events from a JSON file. When the Date lays inside the time period of the event, it should be added to an array, which should be returned at the end of the function.

function getEvents(askDate) {
    var askDate = new Date(askDate);
    var result = new Array();
    $.getJSON(EVENTS_JSON, function(data) {
        $.each(data.events, function(key, entry) {
            if(isInPeriod(askDate.setHours(0,0,0,0), new Date(entry.date[0]).setHours(0,0,0,0), new Date(entry.date[1]).setHours(0,0,0,0))) {
                result.push(entry);
            }
        });
    });
    if(result.length === 0) {
        result = false;
    }
    return result;
}

Unfortunately I get the following error: "TypeError: result.push is not a function".

The isInPeriod function works fine, previously I have had a console output just before the result.push() which has been the JSON object.

JSON looks like:

{
    "events":   [
        {
            "id": 1,
            "name": "Example Event",
            "date": [
                "2014/11/25 07:30:00",
                "2014/11/25 09:00:00"
            ],
            "desc": "Lorem Ipsum sim dolor",
            "image": "http://upload.wikimedia.org/wikipedia/commons/8/84/Example.svg",
            "adress": "Example Road 12",
            "youtube": "https://www.youtube.com/watch?v=_5DqL5-izAY",
            "tags": [
                "Example"
            ],
            "categories": [
                "main_category",
                "sub_category",
                "sub_sub_category"
            ]
        }
    ]
}
Eknoes
  • 508
  • 1
  • 11
  • 24

1 Answers1

6

This is due to the asynchronous nature of $.getJSON. The rest of the outer function is running before the success callback that's looping over your data. Since the rest of the outer function is running, that means because of this:

if(result.length === 0) {
    result = false;
}

result is no longer an array, and therefore doesn't have a push method by the time you attempt to use it. You'll need to restructure your code - see this question for more details.

Community
  • 1
  • 1
James Thorpe
  • 31,411
  • 5
  • 72
  • 93