Array of dynamically typed objects in Typescript

Hello, I am a newbie to Typescript and I recently encountered an issue that has left me stumped. The problem I am facing involves feeding data to a Dygraph chart which requires data in the format [Date, number, number,...]. However, the API I am using provides multiple series of data in the format [Date, number] instead. Is there an elegant way in type script to convert from [Date, number][] to [Date, number, number,...] without resorting to hard coding like the method below? While it does work, the solution feels quite cumbersome and limits scalability beyond 7 series in the same graph.

If you have any suggestions on how to solve this dilemma in a more efficient manner, your assistance would be greatly appreciated!

export class Datapoint {
  date: Date = new Date()
  value: number | undefined
}

export class DatapointSerie {
  datapoints: Datapoint[] = new Array();
}

export class DygraphData {
  maxSeriesCount = 7
  data: [Date, number | undefined, ...number[]] = []

  constructor(series: DatapointSerie[]) {
    let seriesCount = Math.min(series.length, this.maxSeriesCount)
    for (let i = 0; i < seriesCount; i++) {
      this.fillSerie(series[i], i)
    }
  }

  fillSerie(serie: DatapointSerie, index: number) {
    switch (index) {
      case 0:
        serie.datapoints.forEach((datapoint) => this.data.push([datapoint.date, datapoint.value, ...new Array(this.maxSeriesCount - 1).fill(undefined)]))
        break
      case 1:
        // Similar cases for other indexes can be added here
        break

      default:
        break
    }
  }
}

Answer №1

You have the option to utilize the array spread operator when initializing your array:

data: [Date, ...Array<number | undefined>][] = [];

This signifies that any number of elements with type number or undefined may follow the date.

Subsequently, populating the series is as simple as:

  constructor(series: DatapointSerie[]) {
    series.forEach((ser, index) => {
      for (const pt of ser.datapoints) {
        const result: [Date, ...Array<number | undefined>] = [pt.date];
        result[index + 1] = pt.value;
        this.data.push(result);
      }
    });
  }

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

JavaScript's async function has the capability to halt execution on its own accord

Presented here is a JavaScript async function designed to populate a sudoku board with numbers, essentially solving the puzzle. To enhance the user experience and showcase the recursion and backtracking algorithm in action, a sleeper function is utilized b ...

Utilize JavaScript to transform an array into an object using destructuring

Is there a more efficient method to convert a deconstructed array into an object in JavaScript? My current approach involves using the axios API library, and when I make multiple queries simultaneously, I receive an array with 4-5 API responses. I then ne ...

What are the steps to configure Auth0 for an Angular application?

I'm having trouble implementing Auth0 into my angular app. After configuring it on [https://manage.auth0.com/dashboard/], clicking the save changes button results in this error: Error!Payload validation error: 'Object didn't pass validatio ...

Implement a jQuery slider that pauses on hovering

Currently, I am grappling with the clearInterval function in a small jQuery project. To better illustrate the issue, I have created a jsFiddle example: http://jsfiddle.net/eWTSu/ While the rotation works smoothly, I encountered an obstacle when hovering ...

`Firebase User Instance and Custom Firestore Document`

Recently, I posted a question regarding Google Firebase Angular Firestore switchMap and encountered some issues. The question can be found here. After exploring AngularFireAuth, I learned that it is used to create a User object with fixed values, requirin ...

Submitting a form using Ajax that was generated with the help of jQuery

Using a table with various rows, each row has an edit button. Upon clicking the edit button, a form is generated using ajax/json to populate the form data based on the selected row. An issue arises when setting up the ajax for this form. Although the met ...

Expanding Module Scope to Just the Request (employing Require, Node.js)

Original Query The project I am currently working on is using Express to manage HTTP requests. The structure of the project is quite intricate, with multiple embedded require statements. Our main challenge lies in maintaining access to the request and re ...

What is the best way to eliminate transition effects in Vue.js when there are changes in the data

My Vue.js 2.x component fetches data from the server in this way. <template> ... <a href="..." v-if="data.status !== 'blind'">Link</a> ... </template> <script> export default { ... data: { retu ...

Combine several items to form a single entity

When I have two objects returned from the database, my goal is to combine them into one object. Here are the examples: { "id": 4, "first_name": "s", "last_name": "a", ...

Obtain references to templates in component classes

<div> <input #ipt type="text"/> </div> Can the template access variable be retrieved from the component class? For example, is it possible to retrieve it as shown below: class XComponent{ somefunction(){ //Is it possible t ...

Providing structured Express app to deliver HTML and JavaScript content

Currently, I am working with Express and facing a seemingly simple challenge. Here is the structure of my directories: |-config |---config.js |---routes.js |-server.js |-scripts |---controllers |------controllers.js |---directive ...

JavaScript for validating forms in PHP

Hey everyone, I'm struggling to understand why the alert box isn't showing up when I run this code. I'm new to programming and find HTML easy, but I'm currently in a PHP class where we have been tasked with creating and validating a for ...

Utilizing JavaScript for Formatting and Comparing Dates

Here, I would like to compare the current date with a user-inputted date. <script type="text/javascript"> $(document).ready(function(){ $("#date").change(function(){ var realDate = new Date(); var startDate = new ...

Exploring advanced slot functionality in VuetifyJS through autocomplete integration with Google Places API

How can I make VuetifyJS advanced slots work seamlessly with the Google Places API? Currently, some addresses appear in the autocomplete dropdown only after clearing the input text by clicking the "x" icon in the form field. To see the problem in action, ...

Remove a specific NgRx node using LazyLoading technique

I am currently developing an Angular 9 application utilizing NgRx with lazy loading functionality. Upon initial app load, the state appears as follows: However, when navigating to the '/account-config' route, the state changes due to lazy loadi ...

What sets apart `Object.merge(...)` from `Object.append(...)` in MooTools?

This question may seem simple at first glance, but upon further inspection, the MooTools documentation for the 'append' and 'merge' methods appears to be identical. Here is the code snippet provided in the documentation: var firstObj ...

incorrect encoding of Greek characters due to the multer upload package

When uploading files with Greek characters, the uploaded titles are saved as ΠÏξ Îαξ & ÎαÏÏιμιÏαίοι Here is the code for multer variables inside a js file: const storage = multer.diskStorage({ destination: f ...

Angular Material's *matNoDataRow directive is malfunctioning

I am having an issue with using the *matNoDataRow directive in Angular Material. I have created a MatTable with filtering functionality, and when no data matches the filter, I want to display a specific text. However, the directive does not seem to be work ...

Using JavaScript to show content in a textarea field

In my index.jsp file, I have implemented the following code to populate two textareas, INPUT_TEXT and INPUT_TEXT2, with processed data. This involves passing the text through a servlet, a Java class, and finally displaying the preprocessed results in the s ...

What is the best way to prevent the deletion of a specific value in ChipInput (material-ui-chip-input)?

Incorporating the chip input feature from material-ui-chip-input into my project has been great for entering emails. However, I am faced with a challenge - I need to disable the ability to delete specific values. Specifically, when populating the input f ...