What is the correct way to express an object in an array?

I've encountered an issue: I'm working with an array called _daysConfig<DayConfig>

When I manually populate it like this, everything functions correctly:

_daysConfig: DayConfig[] = [
{
  date: new Date('Wed Jul 22 2020 21:06:00 GMT+0200 (heure d’été d’Europe centrale)'),
  subTitle: 'x',
  marked: true
},
{
  date: new Date('Wed Jul 31 2020 21:06:00 GMT+0200 (heure d’été d’Europe centrale)'),
  subTitle: 'y',
  marked: true
},  ];

However, when I attempt to fill it using another array(allEvents) and the .push() method, it stops working:

this.allEvents.forEach(element => {
  this._daysConfig.push(
    {
      date: new Date(element.startTime),
      subTitle: 'x',
      marked: true
    },
);
});

Upon inspection in the Chrome console, the output appears like this:
https://i.sstatic.net/dtVm4.png

If anyone could provide assistance, I'd greatly appreciate it.

EDIT :

I attempted this approach

Try pushing the "DayConfig" object instead of a standard object.

this.allEvents.forEach(element => { 
    this._daysConfig.push(
        new DayConfig({
            date: new Date(element.startTime),
            subTitle: 'x',
            marked: true
        })
    );
});

Or consider something like this

this.allEvents.forEach(element => { 
  const obj = new DayConfig();
  obj.date = new Date(element.startTime);
  obj.subTitle = 'x';
  obj.marked = true;
  this._daysConfig.push(obj);
});

Unfortunately, these methods didn't yield the desired results.

Note that DayConfig is not an object, but rather a type.

Here's a snippet of my code :

 import { Component, ViewChild } from '@angular/core';
import { CalendarComponentOptions, CalendarComponent, DayConfig } from '../../assets/ion2-calendar';
import * as moment from 'moment';
import { AngularFireDatabase } from '@angular/fire/database';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {


  @ViewChild('calendar', { read: CalendarComponent }) calendarRef: CalendarComponent;

  dateRange: { from: string; to: string; };
  date: string;
  type: 'string';
  typeEvent: string = 'task';
  dateDay: number;
  viewDate: Date;
  user: string = 'Clémentine';
  showAddEvent: boolean;
  i = 0;

  newEvent = {
    user: '',
    title: '',
    description: '',
    startTime: '',
    startHour: '',
    place: '',
    repeat: '',
    altern: false
  };

  ...
...

Additionally, you can refer to my chrome console for more insights : Chrome Console

Answer №1

It seems like the issue at hand is related to timing: within the constructor, you are calling the loadEvents() method. This method subscribes to an observable, meaning that all code within the subscribe block will only be executed once the result of

this.afDB.list('Events').snapshotChanges(['child_added'])
has been returned. Since this process may take some time, your console.log() calls may execute before the array _daysConfig is populated. To address this, consider moving your log messages from the constructor to the end of the daysConfig() method for a more accurate console output.

Additionally, keep in mind that you cannot use new DayConfig() as DayConfig serves as a type rather than a class.

Answer №2

Consider pushing the "DayConfig" object instead of a regular object.

this.allEvents.forEach(element => { 
        this._daysConfig.push(
            new DayConfig({
                date: new Date(element.startTime),
                subTitle: 'x',
                marked: true
            })
        );
    });

You could also try this approach:

this.allEvents.forEach(element => { 
    const obj = new DayConfig();
    obj.date = new Date(element.startTime);
    obj.subTitle = 'x';
    obj.marked = true;
    this._daysConfig.push(obj);
});

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

What is the best way to interpret numerous rows of Form elements simultaneously?

What is the most efficient way to name form elements across rows for easy conversion into JSON format? Considering HTML does not have built-in Array support, what alternative method should be used? In each row, there are 2 text fields and 1 select dropdow ...

Visual feedback: screen flashes upon clicking to add a class with jQuery

I have successfully added a click event to my pricing tables in order to apply an animation class on mobile devices. However, I am facing an issue where every time I click on a pricing option on my iPhone, the screen flashes before the class is applied. Is ...

Combining two-digit values

As a newcomer to JavaScript, I've been working on creating a basic calculator to practice my skills. However, I've run into an issue. When entering a double-digit number, the calculator is adding the digits together instead of treating them as se ...

Challenges faced when attempting to launch a React-powered application on Railway platform

When I transferred my fullstack app (React + Express) from Heroku, I encountered an issue. React apps need to be built to run and require necessary dependencies installed, but typically only raw source code is stored on Git. A typical structure for fullst ...

Tips for updating data within an array using a copied object

Just starting out with JavaScript Could you assist me with a basic inquiry, please? For instance, I have an array like this: const array = [{ id: 1, name: 'Ferrari', type: 'F40', price: '350 000$', countr ...

Developing a Multi-Stage Pop-Up with Jquery

I am interested in creating a custom multi-step modal This particular div has dynamically generated classes $('.modal-content').append('<div class="modal-body step step-' + key + '" data-step="'+key+'"></div> ...

The URL may change, but the component remains constant when navigating back

My application consists of two primary components: the Project component and MainContainer. The MainContainer component regularly fetches data using a fetchData method. When moving forward, both the URL and component can change dynamically. However, when m ...

Animating object on display and returning it with keyframes

Given the code snippet below: <div class="leftBox"> <div class="mainNode" ></div> </div> <script type="text/javascript"> $('.mainNode').click(function() { var element = $('.mainNode'); if (!ele ...

Updating Vue.js Component Data

I have set up a basic Example Component which is bound to a Vue Instance as shown below: <template> <div class="container-fluid"> <div class="row"> <div class="col-md-8 col-md-offset-2"> < ...

Angular 5 - Deleting DOM Elements Causes View to Remain Stale

I am experiencing an issue with a tag type search functionality on my website. The search has two columns in the view, with the right column for categories and the left for subcategories. When a user clicks on a category tag, I use buttons to display a sel ...

"Clicking on the jQuery carousel dots results in always navigating back to the first item

Creating a carousel using basic jquery, utilizing the .css() rule to toggle opacity between slides. The goal is to have each dot trigger the display of its corresponding slide while hiding the others. Currently trying: $('.dot').click(function( ...

Tips on effectively storing extra object properties across all entries in a MongoDB document group

Currently, I have a node module that involves parsing a .csv file into MongoDB documents. The issue I am encountering is that only the first inserted document contains certain metadata fields, while the rest do not retain these fields. I am seeking guidan ...

Incorporating Tinymce into a dialog with Vuejs & Vuetify may necessitate a refresh

I have implemented tinymce as a component for creating and editing articles In addition, I am using vuetify along with the v-dialog component, and all my form fields are within this modal However, each time I change the instance of the tinymce component, ...

Model in Sequelize does not get updated

I have a basic user model with two simple relationships: export const Password = sequelize.define("password", { hash: { type: DataTypes.STRING, allowNull: false, }, salt: { type: DataTypes.STRING, allow ...

The process of AJAX polling a JSON-returning URL using jQuery's $.ajax() method does not appear to provide up-to-date responses

I am currently working on a project that involves polling a specific URL for a JSON response using AJAX. The initial AJAX request alerts the server of my need for JSON content, prompting it to start building and caching the response. Subsequent AJAX reques ...

Showing numeric values with decimals in an Angular Handsontable table

I want to display a decimal value (22.45) without rounding while using angular-handsontable in my application. Even though I specified the format, the value is not displayed as expected columns: ({ type: string; numericFormat: { pattern: string; }; } | {} ...

Assigning alphanumeric characters to the axis for identification purposes

review the code in index.html <!DOCTYPE html> <html> <head> <title>D3 test</title> <style> .grid .tick { stroke: lightgrey; opacity: 0.7; } .grid path { stroke-width: 0; } .ch ...

Is there a way to transform an HTML table into an Excel file with several sheets?

Is there a way to transform multiple HTML tables into an Excel file with multiple worksheets? I need assistance with this task. You can find an example here function exportTablesToExcel() { var tableContent = "<table border='2px'>< ...

Executing a function immediately upon the start of a new month in JavaScript (Node.js) without relying on any external libraries?

Is it possible to automate the process of creating a document in MongoDB using Mongoose every 1st of a new month, ideally as soon as the date changes without relying on third-party libraries like needle or cronjob? Can this be achieved solely with setInter ...

sending parameters to a callback function that is listening for arguments

function setmclisten(message, sender, sendResponse) { console.log(data); if(message['type'] === 'startUp') { console.log(data); sendResponse(data) } } function QuarryToServer(){ chrome.runtime.onMessage.removeListener( ...