Is there a way to access the value or key of a JSON property in an Angular template for rendering purposes?

Having trouble displaying the JSON values of certain properties on screen.

Utilizing Angular Material table to showcase my JSON response.

The code snippet below is responsible for rendering the JSON data:

 <mat-card-content class="dashboard-card-content">
    <div></div>
    <div *ngIf="card.title===title1" class="custom-table-container mat-elevation-z8">
      <table mat-table [dataSource]="dataSourceGeneralShift" class="">

        <!-- Name Column -->
        <ng-container matColumnDef="Name">
          <th mat-header-cell *matHeaderCellDef> Name </th>
          <td mat-cell *matCellDef="let col" class="align-left"> {{col.Name}} </td>
        </ng-container>

        <!-- day10 Column -->
        <ng-container matColumnDef="day10">
          <th class="table-header" mat-header-cell *matHeaderCellDef> Shift </th>
          <td mat-cell *matCellDef="let col" class="align-left" > {{col | json}} </td>
        </ng-container>

        <tr mat-header-row *matHeaderRowDef="displayedColumns; sticky: true"> </tr>
        <tr mat-row *matRowDef="let row; columns: displayedColumns;"> </tr>
      </table>
    </div>
 </mat-card-content>

In the day10 column, I'm using {{col | json}} to verify API data retrieval!

Need to display Month values from day1 to day31.

The returned JSON value assigns day1 on the 1st of every month, day2 on the 2nd of every month and so forth. Each 'day-' property holds distinct values like 'Shift 1', 'Shift 2' etc.

Every JSON response varies. For instance:

day15 response

[
 {
   "Name": "Bravo",
   "day15": "Shift 1"
 }
]

day20 response

[
 {
   "Name": "Adam",
   "day20": "Shift 2"
 }
]

** Problem:** How to handle the changing key values (day1 to day31) while rendering them in the Angular Material table template?

Answer №1

To extract the array of keys present in a response object, you can simply use the static method Object.keys. If you are certain that there will always be two entries, you can choose the one that is not named Name:

public getDayVal(data){
  Object.keys(data).forEach((k) => {
    if (k !== 'Name') return data[k];
  })
}

If you are unsure about the number of entries, you can use a regular expression (Regex) to detect if it matches a specific pattern:

public getDayVal(data){
  let re = /^day[0-9]+$/;
  Object.keys(data).forEach((k) => {
    if (re.test(k)) return data[k];
  })
}

Then, in your template, you can utilize the above helper function to retrieve the key dynamically:

<td mat-cell *matCellDef="let col" class="align-left" > {{getDayVal(col)}} </td>

Important: I'm omitting some necessary sanity checks in this explanation. It's essential to verify if the helper method will actually return anything and how to handle situations where the desired dayXX key is not found. You have the responsibility to address these issues, as currently, the table may display nothing in the column due to an undefined value from the helper method.

Lastly, consider revising your data model if you have the authority to do so. Storing information in a field name is a fundamental design flaw. An example of a better approach could be:

interface DayIfc {
  Name: string;
  Day: number;
  Shift: number;
}

This revised structure would help resolve the challenges you are facing.

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

Securely transfer data between objects using a for loop

Description I have two similar types that are not identical: type A = { a?: number b?: string c?: boolean } type B = { a?: number b?: string c?: string } I am looking to create an adapter function f() that can convert type A to type B, with ...

What is the procedure for setting up the typings folder in AngularJS 1.5 with TypeScript?

I'm currently working on a project using AngularJS 1.5 and TypeScript. I need to install the "angularjs/angular.d.ts" and "angularjs/angular-route.d.ts" files. Despite installing tsd globally, when I run the command "tsd install angular," I receive a ...

How can I integrate React-Router Link as a component within Material-UI using Typescript?

Hey everyone, I've encountered an issue while trying to utilize Material UI's component prop to replace the base HTML element of a component. Error: The error message reads: Type 'Props' is not generic. This problem arises from the fo ...

Encountering a compilation error due to a Typescript assignment

While working with Typescript, I encountered a compilation error in the code shown below: console.log('YHISTORY:login: data = '+data); let theData = JSON.parse(data); console.log('YHISTORY:login: theData = '+JSON.stringify(theData)); ...

Issue encountered in event.d.ts file at line 74, character 76: TypeScript error TS2370: A rest parameter is required to be an array type

I am currently working on a project in Angular 6 and I encountered an issue while trying to integrate Google Maps into my website. When running ng serve, I received the following errors: ERROR in node_modules/@types/googlemaps/reference/event.d.ts(74,76): ...

Exporting declarations and different export types within a TypeScript ambient module

I am currently working on adding specific types for the config module in our application. The config module is generated dynamically from a JSON file, making it challenging to type. Since it is a node module, I am utilizing an ambient module for the typing ...

An issue occurred: the channel has been terminated within the ChildProcess.target.send function at internal/child_process.js, line 562, character

My Angular 5 application is giving me an error message that says "ERROR in Error: channel closed". This occurs after running the application. The issue seems to persist even though it works fine for a few minutes after executing ng serve. Has anyone else e ...

What is the reason behind the restriction on creating circular dependencies in Ionic applications?

Working with Ionic, I have created 2 services to provide data: export class DocumentService { constructor(favorisService: FavorisService) { } async GetById(id: number): Promise<DocumentModel>{ let path = this.favorisService.getPath(); ...

Does Angular 8 development mode implement tree-shaking?

I am curious to know if tree-shaking occurs during Angular 8 development mode. When running the following command: ng build I understand that tree-shaking happens when I use the command below: ng build --optimization=true|false ...

What is the process for creating static pages that can access local data within a NextJS 13 application?

I recently completed a blog tutorial and I must say, it works like a charm. It's able to generate dynamic pages from .md blog posts stored locally, creating a beautiful output. However, I've hit a roadblock while attempting what seems like a sim ...

How can TypeScript allow an argument to only accept keys that match another argument?

I'm currently developing a library that deals with linked lists. The current implementation is hardcoded to work with a list node type containing a "next" field that points to the next node of the same type. However, I am looking to make it more flexi ...

Custom Validation requires promises to be present

Creating a custom validation method to validate ranges can be done in different ways. Below is an example of how to achieve this: static ratingRange=(min:number,max:number) => { return (control:AbstractControl):Promise<ValidationErrors|null&g ...

Creating dynamic components from JSON elements does not trigger a rerender of components within an array

Imagine having a simplified input structure like this: [ { type: "text", text: "how are you {name}" }, { type: "input", input: "name" }, { type: "text", text: "good to ...

Is there a way to manually trigger a re-render of a component?

I am new to Angular 2 and I'm accustomed to the digest cycle in Angular 1. In Angular 1, when I update the scope of a view, I can manually trigger a digest by calling $scope.$digest(). However, in Angular 2, with its lack of implicit data binding, I&a ...

Understanding Restangular with Typescript can be challenging, especially when dealing with a 'restangularized' response object

In my project, I am working with Angular 1.5.x using TypeScript in combination with restangular to access a remote API. Here is an overview of the scenario: The API endpoint I am connecting to is http://localhost:53384/api/timezones. Making a GET request ...

This phrase cannot be invoked

My code seems correct for functionality, but I am encountering an error in my component that I do not know how to resolve. Can someone please help me with this issue? This expression is not callable. Not all constituents of type 'string | ((sectionNa ...

Error message: Angular 2 JsonpModule import not defined

Within my app.module.ts file, I have the specified code import {NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {JsonpModule} from '@angular/http'; import {AppComponent} from & ...

Delete one item from a group of objects[]

In my TypeScript code, I have a declared object like this: public profileDataSource: { Value: string, Key: number }[]; This results in an object structure that looks similar to the following: 0: Object {Value: "<Select Profile>", Key: null} ...

Using Stack and Drawer Navigations Together in React Native Navigation(v6)

I am looking to merge Stack and Drawer navigations. I have multiple screens and wish to display select screen labels in the drawer tab. <RootNavigatorStack.Navigator> <RootNavigatorStack.Screen name="DrawerTab" component={DrawerNavig ...

What is the process for implementing a type hint for a custom Chai assertion?

As part of my typescript project, I decided to create a custom assertion for the chai assertion library. Here is how I implemented it: // ./tests/assertions/assertTimestamp.ts import moment = require("moment"); import {Moment} from "moment"; const {Asser ...