For Loop for Local Data Entry

Hi!
I’m a student taking a basic app development class, and I could really use some help on a basic issue. I’ve pulled my date data from my database, and I want the calendar to loop through my array and create an event for each date I saved in the database.

I can’t figure out where I can put the loop within the code to make it so the events are uploaded to the amount that exists.

Here is the chunk of code I’m stuck on (I left the for loop in there) I know it works if I remove the loop and hardcode the array identifier (calData[0].calYear)

mobiscroll.eventcalendar(‘#eventcalendar’, {
data : [
for (i = 0; i < calData.length; i++) {
{
start: new Date(calData[i].calYear, calData[i].calMonth, calData[i].calDay),
title: calData[i].calName,
allDay: true,
color: ‘red’
},
}
]
})

Thank you in advance! Big project due in a few days, and I hope this little syntax isn’t what I get stuck on!

Have you tried removing the loop from inside the data array and dealing with it prior to passing it to the data array?
Something along these lines:

var eventData = [ ];
for (var i = 0; i < calData.length; i++) {
eventData.push({
start: new Date(calData[i].calYear, calData[i].calMonth, calData[i].calDay),
title: calData[i].calName,
allDay: true,
color: ‘red’
});
}

mobiscroll.eventcalendar(‘#eventcalendar’, {
data: eventData
});

1 Like

Hi @Jacob :wave:

In your code, you can’t use a for loop directly inside the data array. The data property must be an array of events.

The best practice is to build the array of events outside the component initialization and then pass it to the component.
You can use a for loop to iterate through your data and create the events as Francisco suggested, or you can use the map function for that.

Here’s a quick example using the map function:

const events = calData.map(data => ({
  start: new Date(data.calYear, data.calMonth, data.calDay), 
  title: data.calName,
  allDay: true,
  color: 'red',
}));

// Initialize the mobiscroll eventcalendar component with the events array
mobiscroll.eventcalendar('#eventcalendar', {
  data: events, // Pass the array of events
});
1 Like

Thank you both for your help! This is exactly what I needed!