-2

Possible Duplicate:
Safest Way to Loop Over Javascript Object

I have this hard coded snippet of code in JavaScript and I would like to know if it is possible to make it dynamic with a for loop. My problem is that I don't know exactly how to output the values in the JavaScript file.

function getEventData() {
    return {
        events: [
        {
        "id":1,
        "start": new Date(year, month, day, 12),
        "end": new Date(year, month, day, 13, 30),
        "title":"Check Up"
        },
        {
        "id":2,
        "start": new Date(year, month, day, 14),
        "end": new Date(year, month, day, 14, 45),
        "title":"Free Trial",
        readOnly: true
        },
        {
        "id":3,
        "start": new Date(year, month, day + 1, 17),
        "end": new Date(year, month, day + 1, 17, 45),
        "title": "Consultant"
        },
        {
        "id":4,
        "start": new Date(year, month, day - 1, 8),
        "end": new Date(year, month, day - 1, 9, 30),
        "title":"Check Up"
        }
     ]
    };
}

Thats the hard coded JavaScript code. Is it possible to loop through a list and output the values kinda like this:

for(var i = 0; i < listEvents.lenght; i++)
        {
            {
             "id": listEvents[i].Id,
            "start": listEvents[i].Start,
            "end": listEvents[i].End,
            "title": listEvents[i].Title
            },
        }

Thanks a lot for your help.. much appreciated.

Community
  • 1
  • 1
Christian Agius
  • 309
  • 1
  • 4
  • 13
  • 3
    Well - of course you can make it dynamic - but listEvents already holds your events. Why do you want to loop through the values and assign them again to another object? – madflow May 22 '12 at 08:54

2 Answers2

1

Something like this?

var result = { events: [] };

for(var i = 0; i < listEvents.length; i++)
{
    result.events.push ({
         "id": listEvents[i].Id,
        "start": listEvents[i].Start,
        "end": listEvents[i].End,
        "title": listEvents[i].Title
        });
}
Tim Rogers
  • 21,297
  • 6
  • 52
  • 68
0

Well it looks like you have to create all your "events" at some point in time so to do it in the second way you are showing doesn't make much sense since you would have to populate the "listEvents" array first.

One way of making the code a little bit tidier would be to use a constructor function like so:

var Event = function(id, start, end, title) {
    this.id = id;
    this.start = start;
    this.end = end;
    this.title = title;
    return this;
}

var getEventData = function () {
    return {
        events : [
            new Event("1", new Date(...), new Date(...), "title"),
            new Event("2", new Date(...), new Date(...), "title"),
            new Event("3", new Date(...), new Date(...), "title")
        ]
    }
}
abaelter
  • 887
  • 1
  • 11
  • 22