Managing TypeScript objects

Just starting out with TypeScript and feeling a bit lost. The data I receive from my BackEnd looks like this:

{
    "A": [
        {
            "fieldA": 0,
            "fieldB": "A",
            "fieldC": 123,
            "fieldD": 0,
        },
        {
            "fieldA": 0,
            "fieldB": "A",
            "fieldC": 111,
            "fieldD": 0,
        },
        {
            "fieldA": 0,
            "fieldB": "A",
            "fieldC": 99,
            "fieldD": 0,
        },
        {
            "fieldA": 0,
            "fieldB": "A",
            "fieldC": 24,
            "fieldD": 0,
        },
        {
            "fieldA": 0,
            "fieldB": "A",
            "fieldC": 21,
            "fieldD": 0,
        },
        {
            "fieldA": 0,
            "fieldB": "A",
            "fieldC": 11,
            "fieldD": 0,
        },
        {
            "fieldA": 0,
            "fieldB": "A",
            "fieldC": 75,
            "fieldD": 0,
        },
        {
            "fieldA": 0,
            "fieldB": "A",
            "fieldC": 76,
            "fieldD": 0,
        },
        {
            "fieldA": 0,
            "fieldB": "A",
            "fieldC": 13,
            "fieldD": 0,
        }
    ],

And my TypeScript class structure for handling this data is as follows:

export class someDataFromBackend{
  public data: {
    [key: string]: {
      fieldA: string;
      fieldB: number;
      fieldC: string;
      fieldD: number;
    };
  }[];

  constructor(data: any) {
    this.data = data;
  }
}

My issue at the moment is that I'm struggling to access any of the elements. For example, I want to create a new Array with values from all fieldC. Or perhaps something as simple as printing the fieldC from the second array inside "A" (the one with value 111).

Even when I attempt to console.log(someDataFB.data), it returns undefined.

Answer №1

Your server is sending an array of objects labeled as "A". To access a specific object from this array, you need to follow these steps:

First, create an interface for the object as shown below:

export interface customObject {
  propertyA: dataType,
  propertyB: dataType,
  propertyC: dataType,
  propertyD: dataType
}

Next, use console.log(A[index].field) where index is the position of the object you want to access and field is the property you want to retrieve.

For example, console.log(A[2].fieldB) will output "A".

Answer №2

Your initial typing is incorrect. It should be structured like this:

export class someDataFromBackend{
  public data: {
    [key: string]: {
      fieldA: string;
      fieldB: number;
      fieldC: string;
      fieldD: number;
    }[]; // <--- take note of the array notation
  };
}

As @AhmedSHA256 mentioned, it would be beneficial to define the objects as distinct types for clarity:

export interface AObjects {
  fieldA: type;
  fieldB: type;
  fieldC: type;
  fieldD: type;
}

export interface ServerData {
  A: AObjects[]; // It's advisable to specify this explicitly if the value is known beforehand.
}

export class someDataFromBackend{
  public data: ServerData;
}

When I attempt to console.log(someDataFB.data), it returns as undefined.

This indicates that the data passed to your class in the constructor is undefined. The retrieval logic from the Server appears to be incorrect. Since your code isn't provided in the question, I'm unable to assist further.

Accessing data follows the typical pattern in most languages: this.data.A[2].fieldB

To create a new array containing only the fieldB values is a bit more involved:

const bArray = this.data.A.map(o => o.fieldB);

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

Symfony using Vite with Vue 3 encounters an error: Uncaught ReferenceError - exports is undefined

Currently, I am in the process of developing a Symfony 3 Application with Vite and Vue3 integrated with TypeScript. To replace Symfony's Webpack Encore, I opted for the Vite Buildtool using this convenient plugin: https://github.com/lhapaipai/vite-bu ...

I am having trouble getting ngFor to properly render my accessible data. Whenever I attempt to use it, it ends up breaking my code. Can someone please

When using *ngFor to iterate through data, everything appears to be working fine until attempting to access nested data within an object inside another object. For example: { "tvshow": [ { "id": "value", "time": { "clock": "valu ...

What is the process for eliminating the perplexing "default" attribute that has been inserted into JSON?

I recently came across the jsondata.json file: { "name": "John", "age": 30, "car": "ferrari" } Located in the same directory is a typescript file called main.ts where I simply output the json data using console.log import * as j from '. ...

Unlock the power of TypeScript's inheritance by utilizing static methods for type

In my TypeScript project, I have two classes: BaseModel and HotelModel. The HotelModel extends the BaseModel class, which provides static methods like findById, all, etc. export default class BaseModel { private collection:string _id:string | undefine ...

Unable to locate the reference to 'Handlebars' in the code

I am currently attempting to implement handlebars in Typescript, but I encountered an error. /// <reference path="../../../jquery.d.ts" /> /// <reference path="../../../require.d.ts" /> My issue lies in referencing the handlebars definition f ...

The module '@angular/core' could not be located in the '@angular/platform-browser' and '@angular/platform-browser-dynamic' directories

Attempting to incorporate Angular 2.0.0 with JSMP, SystemJS, and TS Loader in an ASP.NET MVC 5 (non-core) application. Encountering errors in Visual Studio related to locating angular modules. Severity Code Description Project File Line Suppr ...

What steps should I take to resolve the eslint issue indicating that a TypeScript props interface is not being utilized, even though it is being used?

One of my components utilizes AvatarProps for its props: https://i.sstatic.net/cZBl1.png Below is the interface declaration for AvatarProps: export interface AvatarProps { userName: string; userLastName: string; userImg?: string; onPress?: Functi ...

Typescript: When using ts-node-dev, an error occurred while trying to import express due to an unexpected

I am embarking on a fresh project using Typescript and I intend to set up the node server with typescript utilizing express. There's a helpful tutorial that explains how to execute a Typescript file without going through the hassle of compiling files, ...

The correct assertion of types is not carried out during the initialization of generics through a constructor

I am encountering a minor issue with TypeScript, and I am uncertain whether it is due to a typo on my part or if TypeScript is unable to correctly infer the types. Let me provide all the necessary code to replicate the problem: interface IRawFoo { type: s ...

Designate as a customizable class property

I'm struggling to create a versatile inheritance class for my services. Currently, I have two service classes named Service_A and Service_B that essentially do the same thing. However, Service_A works with Class_A while Service_B works with Class_B. T ...

Tips for implementing <mat-progress-bar> in .ts file when making API service requests with Angular

I'm currently utilizing an API call to retrieve an image from a service, and I would like to display a progress bar while the image is being fetched. It seems that I need to incorporate the progress bar within the service as the image data is returned ...

Tips for wrapping text in a column within material-ui's DataGrid

Struggling to apply word wrap to my column header title in DataGrid from material-ui. I've attempted using sx and style with no success. I even tried this: const StyledDataGridtwo = styled(DataGrid)<DataGridProps>(({ theme }) => ({ root: { ...

How can I use Angular to dynamically open a video that corresponds to a clicked image?

I need assistance with a functionality where clicking on an image opens a corresponding video on the next page. The issue is that all images have the same ID, making it difficult to link each image to its respective video. Below is the data I am working ...

Uncovering the mystery of retrieving form values from dynamic HTML in Angular 2

As a beginner in Angular 2, I am facing challenges extracting values from Dynamic HTML. My task involves having some Form Inputs and injecting Dynamic HTML within them that contain additional inputs. I followed the example by @Rene Hamburger to create the ...

Encountering an issue with TypeScript error code TS2322 when trying to assign a className to the @

Encountering a typescript error when trying to apply a className to a Box element. Interestingly, the same code works on other developers' machines with almost identical configurations. Current dependencies: "@material-ui/core": "4.11. ...

Assigning a value to an Angular class variable within the subscribe method of an HTTP

Understanding the inner workings of this process has been a challenge for me. I've come across numerous articles that touch on this topic, but they all seem to emphasize the asynchronous nature of setting the class variable only when the callback is t ...

Customizable parameters in a React component

I am encountering two issues with the code provided below: interface MyForm { age: number; email: string; name: string; } function Form< T, ComponentProps extends { name: string; onChange: (event: React.ChangeEvent) => void; } &g ...

What is the process for extracting Excel .xlsx information from a POST request body in an Express API?

I've created an Angular frontend application that sends an excel (.xlsx) file as form data in the request body to my Express endpoint. Take a look at the function from my Angular service file below: uploadOrder(workOrder: File) { const formData: For ...

Objects in the array are failing to sort in the expected sequence

I am facing an issue with sorting an array of objects by a date property using the lodash function orderBy. I have tried to sort it in both ascending and descending order. var searchObj = [{id: 1, postDate: '2/24/2016 5:08 PM'}, ...

Dealing with "Cannot find name" errors in Typescript when working with React components

I'm currently in the process of transitioning my React code to TypeScript, and I've encountered numerous challenges. One recurring issue is the "Cannot find name" errors that pop up when converting my .js files to .ts files. Let's take a lo ...