I have a little web app. And I use a calender(code from here FullCalendar) there inside a .jsp file.
I use Spring mvc architecture. So when this page loaded a controller which is responsible for this page loading will add an attribute called calendarEventList to the model.
'calendarEventList' is an ArrayList<calObject>. calObject is a class which contain the details about the even.
I can access those details in the jsp by ${calEvent.eventID} where calEvent is an Object from that ArrayList.
In FullCalendar the event load can be called like below
$('#calendar').fullCalendar({
events: [
{
title : 'event1',
start : '2010-01-01'
},
{
title : 'event2',
start : '2010-01-05',
end : '2010-01-07'
},
{
title : 'event3',
start : '2010-01-09 12:30:00',
allDay : false // will make the time show
}
]
});
I want is like below
$('#calendar').fullCalendar({
events: //read the `calendarEventList` and create a suitable array
});
I have title ,start ,end .. details in a Oblect of the calendarEventList.
So I want to create the list which I need to give to the fullcalendar. How can I create such a kind of array in JS.
It's structure should match [{},{},{},...,{},{}] as given in the example. {} includes a detail about one Object in that calendarEventList ArrayList.
any detailed description will be highly appreciated.
If i truly understand your question ( you have array of objects, all objects contains different field, but each object contains title, start (and end)). So your task is filter this array.
Solution:
function factory(array){
return array.map(function(item){
var instance = {title: item.title, start: item.start};
if(item.end) instance.end = item.end;
return item;
});
}
var res = factory([{ item: 1, title: 2, start: 4, an: 123, pp: "asdf"}, { item: 2, title: 2, start: 4, end: 5}, { item: 3, title: 2, start: 4}]);
Output will be filtered array of objects with start, title, (end) fields;
Try demo
Let try with my example:
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var employees = [];
employees.push({ id: 111, title: "Testing Event 001", start: new Date(y, m, d-5,10,30) , end: new Date(y, m, d-5,12,30),className: ['yellow-event', 'black-text-event']});
employees.push({ id: 111, title: "Testing Event 002", start: new Date(y, m, d-3,10,30) , end: new Date(y, m, d-3,12,30),className: ['yellow-event', 'black-text-event']});
on events: employees put like this,,
Hope it help full. thanks you..
Related
I am trying to make a calendar with events that are rendered dynamically.
I use this to create the days for the calendar and create an array to display. I try to create an events object containing the details for the events. When I try to outside of the initialDays map fuction it works fine and is able to find the object with the correct date and time however when I try to use find function inside of the initialDays map function I get this error.
events.find((item) => {
return item.datetime == dates
})
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'length')
createDays()
{
this.today = startOfToday()
this.formatedDate = format(this.today, 'MMM, yyyy')
this.currentMonth = this.formatedDate
this.getNewDays = parse(this.currentMonth, 'MMM, yyyy', new Date())
this.firstDayCurrentMonth = parse(this.currentMonth, 'MMM, yyyy', new Date())
let initialDays = eachDayOfInterval({
start: startOfWeek(this.getNewDays, {weekStartsOn: 1}),
end: endOfWeek(endOfMonth(this.getNewDays), {weekStartsOn: 1})
})
let events = [{ id: 3, name: 'Date night', time: '6PM', datetime: '2022-10-10', href: '#' }, { id: 4, name: 'Date night', time: '6PM', datetime: '2022-10-12', href: '#' }, { id: 3, name: 'Date night', time: '6PM', datetime: '2022-10-13', href: '#' }]
events = events.map((events) => {
return {
id: events.id,
name: events.name,
time: events.time,
datetime: events.datetime,
href: events.href
}
})
const findevent = events.find((item) => {
return item.datetime === '2022-10-10'
})
console.log(findevent)
initialDays = initialDays.map((dates) => {
return {
date: format(dates, 'yyyy-MM-dd'),
isCurrentMonth: isSameMonth(this.getNewDays, dates),
isToday: isToday(dates),
isSelected: isSameDay(dates, this.today),
events: events.find((item) => {
return item.datetime == dates
})
}
})
this.days = initialDays
},
EDIT ***
InitialDays returns a array of dates from start of the current month to end of current month plus 1 week before and 1 week after.
I want the events to be filled in if they match dates. However currently it just fills every date with the all the events. I thought using the find method would work. Date-fns has a ```isSameDay`` function however it only returns true or false. Not sure how to continue...
{
"date": "2022-10-22",
"isCurrentMonth": true,
"isToday": false,
"isSelected": false,
"events": [
{
"id": 3,
"name": "Date night",
"time": "6PM",
"datetime": "2022-10-10",
"href": "#"
},
{
"id": 4,
"name": "Date night",
"time": "6PM",
"datetime": "2022-10-12",
"href": "#"
},
{
"id": 3,
"name": "Date night",
"time": "6PM",
"datetime": "2022-10-13",
"href": "#"
}
]
}
First, let's see the events you are working with:
let events = [{ id: 3, name: 'Date night', time: '6PM', datetime: '2022-10-10', href: '#' }, { id: 4, name: 'Date night', time: '6PM', datetime: '2022-10-12', href: '#' }, { id: 3, name: 'Date night', time: '6PM', datetime: '2022-10-13', href: '#' }]
The items are objects and
const findevent = events.find((item) => {
return item.datetime === '2022-10-10'
})
is working for you, which proves that this is operational.
In the snippet below we can see that map does not work when you want to call it for an object
let initialDays = {
start: new Date(),
end: new Date()
};
initialDays = initialDays.map((dates) => {
return dates.length
})
therefore eachDayOfInterval returns an array (otherwise you would get an error, complaining that map is not a function). So, your function of eachDayOfInterval does something that you did not share, so it's unclear what this array will contain.
However, it is very safe to assume that the eachDayOfInterval returns an array of days (in whatever format). When you do something like
initialDays.map((dates) => {
//...
}
you therefore will iterate your dates and each iteration is a date (day). So the naming of dates above shows that you misunderstood this part and you assumed that you will have an array of dates inside the map callback, but you will have an individual date inside that callback instead, looping through the whole array.
The error suggests that you tried to read the property of length on undefined. This proves the following:
your dates has at least one undefined element, which is the technical reason you get this error
you treat the individual date as if it was an array of dates
items.map(item => something(item))
will loop items and perform a mapping for each item.
I have an Array of objects & each object has a 'start' date & an 'end' date.
sortedDateRanges = [
{
id: 1,
start: "2018-01-01",
end: "2018-01-05",
name: "First item"
},
{
id: 2,
start: "2018-01-02",
end: "2018-01-08",
name: "Second item"
},
{
id: 3,
start: "2018-01-06",
end: "2018-01-13",
name: "Third item"
},
{
id: 4,
start: "2018-01-14",
end: "2018-01-14",
name: "Fourth item"
},
{
id: 5,
start: "2018-02-01",
end: "2018-02-15",
name: "Fifth item"
},
]
I need to sort these objects into groups where each group has NO overlapping date ranges. There are definitely multiple valid outputs. [[{id: 1},{id: 3},{id: 4}], [{id: 2},{id: 5}]] or [[{id: 1}, {id: 3}, {id: 5}], [{id: 2}, {id: 4}]] etc.
My current solution is just comparing each range to the previous range which doesn't produce an incorrect solution...it's just not a comprehensive solution like I am looking for. My current solution returns [[{id: 1}],[{id: 2}],[{id: 3}, {id: 4}, {id: 5}]]
export const groupUnoverlappedItems = sortedDateRanges => {
let groups = [];
let rangeIds = [];
sortedDateRanges.map((current, idx, arr) => {
if (idx === 0) {
groups.push([current]);
rangeIds.push(current.id);
// return result;
} else {
let previous = arr[idx -1];
// check for overlap
let previousEnd = (new Date(previous.end)).getTime();
let currentStart = (new Date(current.start)).getTime();
let overlap = (previousEnd >= currentStart);
if (overlap) {
// if overlap, push new group
groups.push([current]);
rangeIds.push(current.id);
} else if (rangeIds.indexOf(current.id) === -1) {
groups[groups.length -1].push(current);
rangeIds.push(current.id);
}
}
});
return groups;
};
I don't understand if you have a rule to define the groups, or they must be formed dinamically.
Anyway, why don't you get the object with the earliest start date, and use it to create the first object, in the first group.
You have a starting point, then you can find the object with the nearest start date, that doesn't overlap your first object end date. If you proceed sequentially, once you find a date that overlaps, you can be almost safe that is the good one to form the next group.
Once you don't find any other candidates for the first group, then you can check if another group exist (and has at least an object in it), then repeat the process, until all objects are allocated.
May I suggest to use a library, like date-fns, that helps you with useful methods to manipulate dates, and also define date intervals. Javascript has basic support for dates, using a library can save you a lot of time ;)
I have a JSON object that is returned to me from my Web Service which I have added to an array in my AngularJS project.
I need to create a array that looks like this:
$scope.eventSources = [
//this is event source object #1
{
events: [ // put the array in the `events` property
{
title: //POPULATE FROM MY ARRAY,
start: //POPULATE FROM MY ARRAY,
END: //POPULATE FROM MY ARRAY
},
{
title: //POPULATE FROM MY ARRAY,
start: //POPULATE FROM MY ARRAY,
end: //POPULATE FROM MY ARRAY
}
],
}];
from an array that looks like this:
holidays: [
{
HOLIDAY_END: "/Date(1461538800000+0100)/"
HOLIDAY_EVENT_ID: 1
HOLIDAY_START: "/Date(1461106800000+0100)/"
HOLIDAY_TITLE: "Spain "
USER_ID: 1
}
]
So as you can see the HOLIDAY TITLE, HOLIDAY START AND HOLIDAY END need to get added to a new array.
This should be doable with a forEach loop that goes through your holidays and creates an object with the required field from each element in your holidays. This code should do the trick:
$scope.eventSources = [{events:[]}]; //set up object with array for containing data
var func = function() { //Lets do it in a function so it's reusable
holidays.forEach(function(hol) { //forEach loop through the holidays array data
$scope.eventSources[0].events.push({ //Push a new object to our eventSOurces array
title: hol.HOLIDAY_TITLE, //Set up fields on new object
start: hol.HOLIDAY_START,
end: hol.HOLIDAY_END
});
});
}
func(); //Call function to populate array
You switched between END and end in your request, so I've went with end as it's consistent with the other fields.
This is a proposal with Array#map()
var data = {
holidays: [{
HOLIDAY_END: "/Date(1461538800000+0100)/",
HOLIDAY_EVENT_ID: 1,
HOLIDAY_START: "/Date(1461106800000+0100)/",
HOLIDAY_TITLE: "Spain",
USER_ID: 1
}, {
HOLIDAY_END: "/Date(1462538800000+0100)/",
HOLIDAY_EVENT_ID: 2,
HOLIDAY_START: "/Date(1461106800000+0100)/",
HOLIDAY_TITLE: "France",
USER_ID: 2
}]
},
$scope = { eventSources: [{}] };
$scope.eventSources[0].events = data.holidays.map(function (a) {
return {
title: a.HOLIDAY_TITLE,
start: a.HOLIDAY_START,
end: a.HOLIDAY_END
};
});
document.write('<pre>' + JSON.stringify($scope, 0, 4) + '</pre>');
Im trying to loop through an array only i cant seem to extract the data from my array...
http://jsfiddle.net/338Ud/
var listTicker = function (options) {
var defaults = {
list: [],
startIndex: 0,
interval: 3 * 1000,
}
var options = $.extend(defaults, options);
var listTickerInner = function (index) {
if (options.list.length == 0) return;
if (!index || index < 0 || index > options.list.length) index = 0;
var value = options.list[index];
options.trickerPanel.fadeOut(function () {
$(this).html(value).fadeIn();
});
var nextIndex = (index + 1) % options.list.length;
setTimeout(function () {
listTickerInner(nextIndex);
}, options.interval);
};
listTickerInner(options.startIndex);
}
var textlist = new Array({
id: 0,
name: 'Antonia Lallement',
title: '\u003cp\u003e\u003cspan\u003eConsultant\u003c/span\u003e\u003c/p\u003e',
bio: '\u003cp\u003eI started as a resourcer at company three months ago so I\u0026rsquo;m a new team member. Sin...',
image: 'antonia.jpg'
}, {
id: 1,
name: 'Camilla Gobel',
title: '\u003cp\u003e\u003cspan\u003eBusiness Manager\u003c/span\u003e\u003c/p\u003e',
bio: '\u003cp\u003eI joined company in 2011. As a multilingual Consultant, my initial focus was the provisi...',
image: 'camilla.jpg'
}, {
id: 2,
name: 'Mark Dorey',
title: '\u003cp\u003e\u003cspan\u003eDiscipline Manager (Process, Subsea, Project, Safety)\u003c/span\u003e\u003c/p\u003e',
bio: '\u003cp\u003eWhen I joined company I started as a resourcing specialist and worked across Search and ...',
image: 'mark.jpg'
}, {
id: 3,
name: 'Sadia Butt',
title: '\u003cp\u003e\u003cspan\u003eDiscipline Manager (Mechanical, Piping, Structural)\u003c/span\u003e\u003c/p\u003e',
bio: '\u003cp\u003eI couldn\u0026rsquo;t have asked for a better company to work for! After working as a resourc...',
image: 'sadia.jpg'
}, {
id: 4,
name: 'Samantha Linnert',
title: '\u003cp\u003e\u003cspan\u003ePayroll Assistant\u003c/span\u003e\u003c/p\u003e',
bio: '\u003cp\u003eI began at company as an operations assistant learning to spec CVs and post jobs. Shortl...',
image: 'samantha.jpg'
}, {
id: 5,
name: 'Simon Cottenham',
title: '\u003cp\u003e\u003cspan\u003eConsultant, Middle East\u003c/span\u003e\u003c/p\u003e',
bio: '\u003cp\u003eI have been with company for exactly one year now, I never would have believed that I wo...',
image: 'simon.jpg'
}, {
id: 6,
name: 'Vicky Spencer',
title: '\u003cp\u003e\u003cspan\u003ePayroll Manager\u003c/span\u003e\u003c/p\u003e',
bio: '\u003cp\u003eI started my career at company in July 2012 initially covering maternity leave, managing...',
image: 'vicky.jpg'
});
$(function () {
listTicker({
list: textlist,
startIndex: 0,
trickerPanel: $('.textbox'),
interval: 3 * 1000,
});
});
you are adding object to a html .... use . operator to get the actual values
....
options.trickerPanel.fadeOut(function () {
$(this).html(value.id).fadeIn();
//--------^^^----here
}
i am taking id from the object and showing it in the div.. you can add whatever you need there..
$(this).html(value.title).fadeIn(); //to get title
fiddle here
$.each(textlist, function(index, value){
//do stuff with your array
});
Pasting just the diff, i tried to get the data here below.
From the code above.
options.trickerPanel.fadeOut(function () {
$(this).html(value).fadeIn();
});
The diff,
options.trickerPanel.fadeOut(function () {
$(this).html(value.bio).fadeIn();
});
The difference, is value is the entire array object being passed to the fadeOut function, accessing each elements in the array gives the result.
I am trying to use mustache with a bootstrap calendar called Bic_Calendar
basically you can add events to the calendar with an object like this
var events = [
{
date: "28/10/2013",
title: 'DUE DAY ENROLMENT',
},
{
date: "29/10/2013",
title: 'DUE DAY PAYMENT',
},
{
date: "31/10/2013",
title: '1st DAY OF CLASS',
},
]
;
what I want is using mustache to have a quick summary of the next events, the problem is that in order to mustache render the
template the object needs to be change to:
var events = {"events": [
{
date: "28/10/2013",
title: 'DUE DAY ENROLMENT',
},
{
date: "29/10/2013",
title: 'DUE DAY PAYMENT',
},
{
date: "31/10/2013",
title: '1st DAY OF CLASS',
},
]}
;
so I am trying to concatenate the original event into a new one but it is not working, so i guess i am doing something wrong in the concatenation
var events1 = '{"events": '. concat(events) .concat('}');
var events1 = '{"events": ' + events + '}';
non of this options works!
var events is not JSON. It is a literal javascript array, you should not be concatenating it, but simply nesting it in a new object and then serializing into JSON if you need a JSON string.
var events = [
{
date: "28/10/2013",
title: 'DUE DAY ENROLMENT',
},
{
date: "29/10/2013",
title: 'DUE DAY PAYMENT',
},
{
date: "31/10/2013",
title: '1st DAY OF CLASS',
},
];
var nestedEvents = { 'events': events };
var jsonEvents = JSON.stringify(nestedEvents);
As a general rule of thumb, if you find yourself tempted to manually build a JSON string, you are probably not taking the right approach. Build the data structure you want to serialize into JSON first, then serialize it.
The other takeaway, which seems to be a common point of confusion for developers, is that JSON is nothing more than a serialized string representation of some data structure. There is no such thing as a JSON object. The JSON format certainly bears a strong resemblance to a javascript object literal, but it is truly different and should be treated as such. In this case your events variable does not contain a JSON string, so you should not expect to be able to concatenate it as if it were a string.
You have an array of objects like
var events = [
{
date: "28/10/2013",
title: 'DUE DAY ENROLMENT',
},
{
date: "29/10/2013",
title: 'DUE DAY PAYMENT',
},
{
date: "31/10/2013",
title: '1st DAY OF CLASS',
}
];
Just make a new object with your event array like this
var eventsObj = { 'events': events };
If you need to make it a json string then you may use JSON.stringify, which will convert an object to json string. BTW, concat is array objects' method.