Guide on assigning a class to an array of JSON objects in TypeScript

If I have an array of JSON objects, how can I cast or assign the Report class to it?

console.log('jsonBody ' + jsonBody);
// Output: jsonBody [object Object],[object Object]

console.log('jsonBody ' + JSON.stringify(jsonBody));
// Output: jsonBody [{"created_at":"2016-02-04","updated_at":"2016-02-04 00:45:56.000"}, {"created_at":"2016-02-04","updated_at":"2016-02-04 00:45:56.000"}]

// TypeScript class
export class Report {
  created_at!: Date;
  updated_at!: Date;
}

Answer №1

Develop a constructor that can handle JSON object parameters:

class ReportData {
  dateCreated!: Date;
  dateUpdated!: Date;
  
  constructor({dateCreated, dateUpdated}: {dateCreated: string, dateUpdated: string}) {
      this.dateCreated = new Date(dateCreated);
      this.dateUpdated = new Date(dateUpdated);
  }
}

let jsonData = [{"dateCreated":"2016-02-04","dateUpdated":"2016-02-04 00:45:56.000"}, {"dateCreated":"2016-02-04","dateUpdated":"2016-02-04 00:45:56.000"}];

let dataArray: ReportData[] = jsonData.map(obj => new ReportData(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

Leveraging the power of Angular 5 to seamlessly integrate two distinct components on

I am exploring a way to render an additional component on the current page instead of navigating to a new one. Here is my setup: <button mat-button color="primary" [routerLink]="['/tripspath', trip.tripId]" style="cursor: pointer">View Rou ...

Encountering an error code TS5055 when attempting to call an API within a TypeScript constructor

I'm attempting to retrieve a list of customers by calling a GET API from a dashboard constructor as shown below: // tslint:disable-next-line:max-line-length constructor(public addCustomerDialog: MatDialog, private router: Router, private rout ...

Retrieving a specific value from a JSON JDBC column in Spark Scala

Within the mysql jdbc data source used for loading data into Spark, there is a column that contains JSON data in string format. // Establish JDBC Connection and load table into Dataframe val verDf = spark.read.format("jdbc").option("driver&q ...

Using AngularJS to fill a dropdown list with a basic Map using ng-options

I've encountered an issue that I'm struggling with. I am trying to populate a select element in my angular project. Typically, when populating selects, I use JSON data structured like this: [{"id":1, "value":"A"},{"id":2, "value":"B"},{"id":3, " ...

React Typescript: excluding a property in a higher order component

Is it possible to write Typescript type definitions that properly expose the Props type of a component created by a HOC? I want to infer the type of props of the wrapped component and remove any properties provided by the HOC. For example, if we have a HO ...

What are the solutions for resolving 'undefined' errors while working with TypeScript Interfaces?

When working with TypeScript in my Next.js project, I encountered the following error message: Type '{ banner: { id: number; bannerImageUrl: string; } | undefined; }' is not assignable to type 'IntrinsicAttributes & Banner'. Prope ...

In TypeScript, this regular expression dialect does not permit the use of category shorthand

Recently, I attempted to implement a regular expression in TypeScript: I ran the following code: const pass = /^[\pL\pM\pN_-]+$/u.test(control.value) || !control.value; To my surprise, an error occurred: "Category shorthand not allowed in ...

What is the proper way to utilize a class with conditional export within the Angular app.module?

This query marks the initiation of the narrative for those seeking a deeper understanding. In an attempt to incorporate this class into app.module: import { Injectable } from '@angular/core'; import { KeycloakService } from 'keycloak-angul ...

loading JSON file using dynamic JavaScript techniques

My Raspberry Pi is running a C++ application in the background that performs complex mathematical calculations based on sensor input and generates results every second. I want to showcase this data on a website by having the application create a JSON file ...

What is the procedure for obtaining FlowNode in the typescript ast api?

Trying to access and resolve foo and bar from the nodes variable. Upon examination in ts-ast-viewer, it is evident that TypeScript recognizes foo and bar within the nodes node under the FlowNode section (node -> initializer -> elements -> escaped ...

The specified file cannot be found within the Node file system

I am working on a project that involves reading a file using Node fs, and I have the following code: const files: FileSystemTree = { "Component.tsx": { file: { contents: fs.readFileSync( `../../apps/components ...

Developing a functionality to search for specific values within JSON properties

Hello, I have a question about implementing a partial search on a specific property within JSON data. Basically, what I'm trying to achieve is that if I type in "Jac" into the input field, it will search the JSON data for similar strings like Jacob, J ...

Issue with ToggleButtonGroup causing React MUI Collapse to malfunction

I'm having trouble implementing a MUI ToggleButtonGroup with Collapse in React. Initially, it displays correctly, but when I try to hide it by selecting the hide option, nothing happens. Does anyone have any suggestions on what might be causing this ...

NestJs Function yielding inconsistent results based on its calling location

There is a puzzling issue that I am unable to solve. I have stored priceHistories in memory within an array. Strangely, when I invoke a get method, the returned value varies depending on where the method is called from. This is the original property and m ...

The new data is not being fetched before *ngFor is updating

In the process of developing a "Meeting List" feature that allows users to create new meetings and join existing ones. My technology stack includes: FrontEnd: Angular API: Firebase Cloud Functions DB: Firebase realtime DB To display the list of meeting ...

Obtain the data from a service that utilizes observables in conjunction with the Angular Google Maps API

In my Angular project, I needed to include a map component. I integrated the Google Maps API service in a file called map.service.ts. My goal was to draw circles (polygons) on the map and send values to the backend. To achieve this, I added event listeners ...

An effective method for adding information to a REDIS hash

My current computing process involves storing the results in the REDIS database before transferring them to the main database. At the moment, I handle operations in batches of 10k items per chunk using a separate GAE instance (single-threaded computing wi ...

Is there a way to prevent prettier from automatically adding a new line when formatting HTML tags with ">"?

While navigating through the Prettier extension in Vscode, I am struggling to find a way to disable a specific scenario. In particular, I am having trouble with the formatting of an html tag. Below is a snippet of code that requires some adjustments whene ...

Error: Class cannot be loaded by React Webpack loader

I'm encountering an issue with my two typescript packages - a React application and an infrastructure package. The React app has a dependency on the infrastructure package (currently linked via npm). After adding a new class to the infrastructure pack ...

Building AngularJS directives using CSS classes

My current approach is as follows: class AService { $http: any; $state: any; static $inject = ['$http', '$state']; constructor($http, $state) { this.$http = $http; this.$state = $state; }; Dealing w ...