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

Utilizing ng-options within an ng-repeat to filter out previously chosen options

Facing a simple problem and seeking a solution. I am using ng-repeat to dynamically create select boxes with ng-options displaying the same values. The ng-repeat is used to iterate through model options. <div data-ng-repeat="condition in model.condit ...

Run the *.js file only when the current month is December

Alright, I'm stumped. I've been trying to create this script: <script> $(document).ready(function(){ var d = new Date(); n = d.getMonth(); if (n == 11) { src="extrafiles/effect/snow.js"; } }); </script& ...

When employing UI-Router, custom directives may not function properly within nested views

I was developing an angular application using phonegap, ionic, and angular. I had created a custom directive that registered an event listener for the element to activate iScroll upon loading. Initially, the directive worked perfectly when all the views we ...

Stop the occurrence of OpenCPU javascript error pop-up notifications

I'm currently experiencing an error related to CORs during a test deployment of OpenCPU. While I may create a separate question for this issue in the future, for now, I am wondering if it is possible for the deployment to fail without alerting the end ...

Every time Chrome on Android returns a keyCode of 229

Here is a snippet of code that I am having trouble with: ... @HostListener('keydown', ['$event']) onKeyDown(evt: KeyboardEvent) { console.log('KeyCode : ' + evt.keyCode); console.log('Which : ' + evt.which); ...

The AngularJS directive is being triggered before the Jquery AJAX request is completed

I am currently facing an issue where the chart in my AngularJS application (using NVD3.org) is loading before the AJAX call completes and data is fetched. How can I ensure that the chart waits for the AJAX call to finish? <script> var dataxx= ...

Customize MUI 5 input label background color for your own component

Struggling with overriding the background color for a MUI 5 input label on focus in a specific component? I successfully changed it to blue globally in my _theme.js file, but now need to make it red for my KeywordSearchTextField in index.js following MUI ...

Step-by-step guide to installing gatsby-CLI on Windows without requiring admin permissions

Currently, I am facing an issue while trying to install the gatsby CLI using the following npm command: npm install --global gatsby-cli I suspect the problem might be due to lack of admin access. Does anyone have suggestions on how to resolve this error? ...

What is the process of retrieving an image file in a Java post API when it is being transmitted as form data through Jquery?

I have encountered an issue with fetching file data in my POST API when utilizing three input file fields in JavaScript. The values are being sent using formdata in jQuery upon clicking the submit button, but I am experiencing difficulties in retrieving th ...

Issue with setting and showing the PHP data array within the vue.js variable

I am encountering an issue with transferring an array of data from a PHP session variable to a Vue.js variable Here is how I am trying to assign an array of data to a Vue.js variable: permissions:['<?php echo json_encode($_SESSION['permission ...

Tips for preventing Chrome from masking the background image and color on an autofill input

Google Chrome Browser has caused the background-color and background-image effects to be removed from the Username and Password input fields. Before autocomplete https://i.stack.imgur.com/Ww7Hg.png After autocomplete https://i.stack.imgur.com/hbG2C.png ...

Enhancing a specific element in a view using Node.js alongside Express and EJS

My goal is to modify value2 on the server side and update the view accordingly. The question at hand is: How can I efficiently refresh the view with only the new value2? Server: var express = require("express"); var app = express(); app.set('view ...

Is it possible to nest clicks for ajax calls within the results of a previously appended call?

As I dive into learning about AJAX to enhance page loading speed by avoiding reliance on PHP for displaying results, I've encountered a challenge. I have three tiers of data distributed across three database tables: The first tier of data is fetche ...

Stop users from being able to select or highlight text within a content editable div

Is there a method to develop a content-editable div where users are unable to select or highlight content, but can still input information? I'm interested in creating an interface that forces users to delete and enter data character by character, with ...

Having trouble getting my Win and Lose Divs to display in my IF statement within the Card Game

Currently, I am developing a card game where players are presented with a card generated by the computer. The player has to decide whether the next card will be higher, lower, or equal to the current one by clicking corresponding buttons. if ((playerChoic ...

Issues with React - Material UI Menu functionality

I'm encountering an issue with the menu/menu item component from material ui when trying to render it based on a condition. Here is my code snippet... const AddSelectItemButton = () => { return ( <> <Fab ar ...

Sending an AJAX request to a server with ASP.NET Core, including both properties and files

I'm facing an issue with passing an object to the ASP.NET Core Controller that includes user-selected files. Currently, all properties are being passed except for the files. How can I modify the request to ensure the files are included in the object? ...

The fetch function consistently executes the then() block, regardless of any errors, resulting in an undefined response

I'm encountering an issue where the catch block doesn't seem to be firing in my code, even though I am throwing a new error. However, the then block with an undefined response always fires. Can anyone help me understand why this is happening? Ca ...

iOS Chrome: Enabling Cookies with "Always Allow"

While the Safari browser on OSX has a setting under Privacy & Security -> Block Cookies -> Always Allow, enabling the storage of entries in the browser's local storage even when accessing pages from third party sites like those running in an iframe, I ...

Difficulty recognizing sessions in production for a self-hosted Next.js application using Clerk Dev Auth

Having trouble finding the next step in debugging as I couldn't resolve the issue on Clerk's Discord or GH Issues. It seems like it might be a Next.js problem rather than a Clerk one? I am currently running a self-hosted next.js app in a docker ...