Can you tell me how to add a variable to an array of objects in JavaScript?

I am currently engaged in a small project aimed at:

  1. Reading data from a CSV file (such as employee names and shifts)
  2. Displaying this data on FullCalendar.

How can I incorporate the CSV result into this line of code: { id: 'a', title: 'Auditorium A' },

For example, is it possible to achieve this with: { id: data[0], title: data[1] }

Below is the script for reading the CSV file:

<script>
    //Read CSV
    $(document).ready(function() {
        $.ajax({
            type: "GET",
            url: "data.txt",
            dataType: "text",
            success: function(data) {processData(data);}
         });
    });
    
    function processData(allText) {
        var allTextLines = allText.split(/\r\n|\n/);
        var headers = allTextLines[0].split(',');
        var lines = [];
    
        for (var i=1; i<allTextLines.length; i++) {
            var data = allTextLines[i].split(',');
            if (data.length == headers.length) {
    
                var tarr = [];
                for (var j=0; j<headers.length; j++) {
                    tarr.push(headers[j]+":"+data[j]);
                }
                lines.push(tarr);
            }
            console.log(allText);
            return allText[0];
        }

    }

Here is the code snippet related to FullCalendar that needs modification:

document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');

  var calendar = new FullCalendar.Calendar(calendarEl, {
    height: '100%',
    aspectRatio: 1.8,
    editable: false, // enable draggable events
    now: '2020-09-07',
    scrollTime: '00:00', // undo default 6am scrollTime
    headerToolbar: {
      left: 'today prev,next',
      center: 'title',
      right: 'resourceTimelineDay,resourceTimelineThreeDays,timeGridWeek,dayGridMonth,listWeek'
    },
    initialView: 'resourceTimelineDay',
    views: {
      resourceTimelineThreeDays: {
        type: 'resourceTimeline',
        duration: { days: 3 },
        buttonText: '3 days'
      }
    },
    expandRows: true,
    resourceAreaHeaderContent: 'Employees',
    
    resources: [
    
      { id: 'a', title: 'Auditorium A' },
      { id: 'b', title: 'Auditorium B', eventColor: 'green' },
      { id: 'z', title: 'Auditorium Z' }
    ],


    events: [
      { id: '1', resourceId: 'b', start: '2020-09-07T02:00:00', end: '2020-09-07T07:00:00', title: 'event 1' },
      { id: '2', resourceId: 'c', start: '2020-09-07T05:00:00', end: '2020-09-07T22:00:00', title: 'event 2' },
      { id: '3', resourceId: 'f', start: '2020-09-07T00:30:00', end: '2020-09-07T02:30:00', title: 'event 3' }
    ]
  });

  calendar.render();
});

Answer №1

If you want to optimize the loading of data and creation of a calendar, I suggest using ajax to fetch the data first, then processing it before generating the calendar. Here's an example of how you can achieve this:

    $.ajax({
        type: "GET",
        url: "data.txt",
        dataType: "text",
        success: function(data) { createCalendar(processData(data)); }
     });

Next, you can encapsulate the calendar initialization in a separate function and map the fetched data into a usable array of objects like so:

resources: data.map(e => ({id: e[0], title: e[1] })),

Putting it all together:

let calendar; // store your calendar object reference outside the function
function createCalendar(data) {
  calendar = new FullCalendar.Calendar(calendarEl, {
    height: '100%',
    aspectRatio: 1.8,
    editable: false, 
    now: '2020-09-07',
    scrollTime: '00:00', 
    headerToolbar: {
      left: 'today prev,next',
      center: 'title',
      right: 'resourceTimelineDay,resourceTimelineThreeDays,timeGridWeek,dayGridMonth,listWeek'
    },
    initialView: 'resourceTimelineDay',
    views: {
      resourceTimelineThreeDays: {
        type: 'resourceTimeline',
        duration: { days: 3 },
        buttonText: '3 days'
      }
    },
    expandRows: true,
    resourceAreaHeaderContent: 'Employees',
    resources: data.map(e => ({id: e[0], title: e[1] })),    
    events: [
      { id: '1', resourceId: 'b', start: '2020-09-07T02:00:00', end: '2020-09-07T07:00:00', title: 'event 1' },
      { id: '2', resourceId: 'c', start: '2020-09-07T05:00:00', end: '2020-09-07T22:00:00', title: 'event 2' },
      { id: '3', resourceId: 'f', start: '2020-09-07T00:30:00', end: '2020-09-07T02:30:00', title: 'event 3' }
    ]
  });

  calendar.render();
});
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Achieving dynamic serving of static files using Rollup and integrating seamlessly with node-resolve

Currently, I am in the process of building a library using TSDX, which is a powerful CLI tool for package development based on Rollup. My project involves a collection of country flags SVGs that need to be imported and displayed dynamically when required. ...

Error encountered with select2 when using a remote JSONP dataset

When attempting to query the Geonames data using select2, everything seems to work fine with formatting the results. However, an error occurs once the results are populated, which I suspect is preventing the formatSelection function from running properly. ...

Having trouble getting ngAnimate to work properly?

I am facing an issue with ngAnimate dependency injection. For some reason, whenever I add ngAnimate as a dependency in my JavaScript code, it does not seem to work. It's definitely not the script... Here is the HTML code snippet: <!doctype html& ...

convert a screenplay to javascript

I have a script that can be used to calculate the distance between 2 coordinates. The code is a combination of PHP and JavaScript. I am interested in moving it into a standalone JavaScript file but not sure how to proceed. Below is the script related to & ...

Creating a javascript function to update content on click

Recently, I've been designing a webpage and encountered an issue. I want the text in a specific area to change whenever a user clicks on a link. Below is the code snippet related to the section I want to modify using a JavaScript function. <div id ...

Ascending with Progress Indicator Slider

After successfully creating a Bootstrap 5 Carousel with an automated count for each slide (limited to 4) and a corresponding progress bar, I encountered an issue with getting the previous button to function correctly. While clicking the next button works s ...

Tips for creating a data table with nested lists within lists?

I am looking to create a table with data that includes a nested list of grades within a list of students. Is it possible to achieve this and if so, how can I do it? The object structure is as follows: public class Student { public string Num ...

Encountering an issue with Jest when using jest.spyOn() and mockReturnValueOnce causing an error

jest --passWithNoTests --silent --noStackTrace --runInBand --watch -c jest-unit-config.js Project repository An error occurred at jest.spyOn(bcrypt, 'hash').mockRejectedValue(new Error('Async error message')) Error TS2345: The argum ...

Preventing the submission of form post values by using jQuery remote validation

     Within my form, I have incorporated two submit buttons (save & exit, next) and implemented remote email address duplication checks. Everything is functioning properly, however, upon submission of the form, I am unable to determine which specific s ...

Access your account and modify the div section to display a personalized greeting like "welcome $username"

I am currently using a div element to show the user, password, and login button. Additionally, I have implemented AJAX to notify users of an "invalid login" without having to refresh the page. What I am trying to achieve is: Upon successful login, hide ...

NodeJS function does not pause for the PostgreSQL database call despite using await keyword

I am attempting to recursively insert entries into the database where each entry depends on the previous one (the ID of the previous entry will be the child_id of the next entry). However, I am facing difficulties in getting async/await to work correctly. ...

Exploring the Benefits of Combining Vue.js with Laravel

Being a newcomer to Vue, I decided to try it out in a recent project and quickly understood why it's so popular. Everything was running smoothly until I tested it in IE, where nothing seemed to work at all. Encountering errors like Object doesn' ...

Tips for accessing another page when location.state is missing

In my react application, I am passing state through react router and accessing it in the target component/page using the location object. Everything works perfectly fine initially, but when I close the tab and try to open the same page by pasting the URL i ...

Sketch the borders of the element (animated)

Seeking a way to create a button with an animated border that looks like it is being drawn. Current progress involves some code, but it's not working smoothly with border-radius set. (keep an eye on the corners) https://codepen.io/anon/pen/MbWagQ & ...

Angularjs - Navigating the Depths of OrderBy: Effective Strategies for Handling Complex Sorting Structures

I have a collection of Incidents (displayed as an array below) that I need to sort meticulously by State, Priority, and Start_date. Specifically, I want them ordered in the sequence of Initial > Ongoing > InReview > Resolved for State, then Priori ...

php search query, ultimate calendar outcome

Greetings to all who are reading this, I am currently in the process of developing a calendar system for organizing garage plans. To help others understand how it works, I have created a video tutorial on YouTube. Although I am almost finished with the p ...

"VS Code's word wrap feature is beneficial for wrapping long lines of text and code, preventing them from breaking and ensuring they are

text not aligning properly and causing unnecessary line breaks insert image here I attempted to toggle the word wrap feature, installed the Rewrap plugin, and played around with vscode settings ...

Manual mocking in Jest is only effective for the initial function call

In my project, I have created a custom XHR wrapper in utils/xhr.js and I am using Jest manual mocking feature to mock it. However, I am running into an issue where only the first XHR call is being tracked: utils/xhr.js let xhr = { get: function(par ...

What steps should I follow to change the appearance of this object to match this?

Attempting to modify the value of an object nested within an array, which is in another object. The nesting might be a bit complex... Here's how it currently looks { household and furniture: [{…}, {…}], school stuffs: [{…}, {…}] } M ...

Using the .map function on JSON data with and without a parent element in JavaScript

In my current project, I am working on a React + Rails application. For handling JSON data, I typically use the default jbuilder in Rails. However, following the recommendations from the react-rails official documentation, I started adding a root node to m ...