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

Move to the top of the page when the next action is activated

I am working with an Angular 8 application. Within the application, I have implemented navigation buttons for next and previous actions. My goal is to ensure that when a user clicks on the "next" button, the subsequent page starts at the top of the page ...

Issue with loading dynamic content on a webpage using HTML and JavaScript through AJAX

I am currently using the jQuery UI Tabs plugin to dynamically load HTML pages through AJAX. Here is the structure of the HTML code: <div id="tabs"> <ul> <li><a href="pageWithGallery.html" title="pageWithGallery">Gallery< ...

Creating users or custom roles in MongoDB on a NodeJS server is not currently possible

I have been attempting to directly create users on my database through our Express server, utilizing MongoDB 3.4 for the backend. Below is the current code snippet from the server: const express = require('express'); const bodyParser = require(& ...

Issue with resetting the state of a react-select component remains unresolved

I'm currently facing two issues with my react-select component: Firstly, once I select an option, I am unable to change it afterwards. Second, when my form is reset, the react-select component does not reset along with the other fields. For simplici ...

Recover Checkmark Status from Data

Currently, I am storing form data in json format and encountering an issue when trying to load values from a previously created json file. The plain old JavaScript function provided below successfully loads values into a form from a file, effectively resto ...

Save array data to a file in Node.js once it finishes looping

I've been struggling to find a solution to my issue despite looking at examples from other questions. I have created a basic web scraper in nodejs that stores data in an array and now I need help writing this data to a file. I'm having difficulty ...

The Socket.io server running on Express is currently not reachable from any external devices

I currently have a basic application using socket.io and expressjs up and running. The application is hosting a simple HTML file, which I can successfully access through my browser. However, when attempting to access it from other devices on my network, th ...

Using Symfony2 to make an Ajax request in order to show a message based on a particular condition

As a novice in the realm of JavaScript and Ajax, I am struggling to find a way to display a message based on certain conditions. Let's consider a scenario where a user can adjust the quantity of a product they wish to purchase. While implementing thi ...

The hierarchy of script loading in Angular applications

After years of working with MVC, I recently delved into Angular. Although I am well-versed in JavaScript and HTML, I'm still a beginner in the world of Angular. I spent hours troubleshooting my app only to realize that the problem was elusive. The a ...

Tips for managing the second datepicker for the return journey on Abhibus using Selenium webdriver

I am currently working on a code to choose departure date and return journey date, but I am encountering an issue where the return journey date is not being selected. The driver seems to be skipping over the return date selection and proceeding directly to ...

Concatenate data received from PHP to a JavaScript variable and return it

In my current app development project, I have the following code snippet. The variable valdat is sent to a specified URL, processed through a PHP file, and then returned to the app. How can I add the data displayed in the alert message to another variabl ...

Scroll effect for read-only text input with long content inside a div

Is there a way to replicate the scroll functionality of a text input with readonly="readonly"? When the text exceeds the box size, you can highlight and scroll to view it all without a visible scrollbar. I am interested in achieving this effect within a p ...

mongojs implementation that allows for asynchronous query execution without blocking

Forgive me for asking what may seem like a silly question, but I am struggling to make this work. Currently, as part of my learning journey with node.js and mongojs, I have encountered the following issue: Below is my server.js file server.get("/", funct ...

Enhancing TypeScript - Managing Variables within Namespace/Scope

Why is the console.log inside the function correctly logging the object, but after the function returns it logs undefined, failing to update the variable? In addition, when using this within testNameSpace, it returns window. Why is that? namespace testNa ...

The NestJS framework encountered an error due to a method being undefined in the

Encountering Error with NestJS Function create123: TypeError - Cannot read properties of undefined (reading 'create123') The constructor is displayed below \`export class AuthenticationService { constructor( private readonly usersServ ...

Node API is failing to insert user data into MongoDB

I'm currently developing a Restful API using Node.js and storing data in Mongodb, focusing on the user registration API. app.js apiRoutes.post('/signup', function(req, res) { if (!req.body.name || !req.body.password) { res.json({suc ...

Angular 2: Simplifying the Process of Retrieving a Full Address Using Latitude and Longitude

Currently, I am utilizing the angular 2-google-maps plugin. Is there a way to retrieve the country and postal code based on latitude and longitude using Angular 2 Google Maps with Typescript? ...

Use React-table to store the value of an accessor in the state while also utilizing a

I am currently working on implementing a checkbox table using react-table. The primary objective is to have checkboxes in the first column, and upon selection of a checkbox, I intend to store the ID defined in the accessor in the state. Despite going thro ...

Tips for showcasing varied information on Morris Chart

I am working with a Morris chart that is populated with a collection of data, each item containing 6 different data values. My goal is to switch between displaying two different sets of data. For example, I want to show the 'Target' data always ...

Using NodeJS and Express together with Ajax techniques

I am currently developing a web application that utilizes Ajax to submit a file along with some form fields. One unique aspect of my form is that it allows for dynamic input, meaning users can add multiple rows with the same value. Additionally, the form i ...