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

The error message "Declaration file for module 'mime' not found" was issued when trying to pnpm firebase app

Currently, I am in the process of transitioning from yarn to pnpm within my turborepo monorepo setup. However, I have run into an issue while executing lint or build commands: ../../node_modules/.pnpm/@<a href="/cdn-cgi/l/email-protection" class="__cf_e ...

Creating an Http interceptor in Ionic 3 and Angular 4 to display a loading indicator for every API request

One of my current challenges involves creating a custom HTTP interceptor to manage loading and other additional functions efficiently. Manually handling loading for each request has led to a considerable increase in code. The issue at hand: The loader is ...

Using *ngIf to construct SVG icons in Angular 2 doesn't contribute to the DOM in any way

I am currently utilizing icoMoon to import a series of SVG icons. The structure of the html I'm trying to create using ngIf is as follows: <div class="contactIcon"> <svg class="icon icon-envelop"> <use xlink:href="symbol-d ...

Creating a custom `onSubmit` function with Formik, TypeScript, and hooks can be a powerful way

I'm currently creating form onSubmit functions utilizing the useCallback hooks specifically designed for use with the formik library. A sample structure of my component using formik would be as follows: import { useContactForm } from './useCon ...

Issues with include and exclude directives in tsconfig.json are causing problems

I am currently working on a web project that involves organizing folders. Within my project structure, I have subfolders like the following: src/app/shared/models src/app/shared/services src/app/shared/types Each of these subfolders contains additional ...

The property '.....' is missing an initializer and has not been explicitly assigned in the constructor

I want to address an issue with a similar question title that was asked 5 years ago on Stack Overflow. The problem is related to declaring a variable as an array of a specific object type in an Angular component using TypeScript 4.9. Even though I tried t ...

Guide to transforming an IdentityMap<String, dynamic> into a UInt8List

I have a cloud function that generates a JavaScript Buffer object, which looks something like this: functions .region("europe-west2") .runWith({ timeoutSeconds: 20, memory: "128MB", }) .https .onCall(asyn ...

Examining the array to ensure the object exists before making any updates in the redux

Is there a way to determine if an object exists in an array and update it accordingly? I attempted to use the find method, but it couldn't locate the specified object. I also tried includes, but it seems to be unable to recognize the item within the ...

The font awesome symbol is not showing up in the nz-th element

I've encountered an issue with the code snippet below: <th [ngSwitch]="sortIcon" nz-th class="centered" (click)="toggleSortOrder()" nzSort="Stopped">Sort <i *ngSwitchCase="sortEnum.NoSort" class="fa fa-lg fa-fw fa-sort"></i> ...

Encounter an Unexpected Token Issue when using NextJS-auth0 in Jest

I am facing a problem with my Next.js app that is integrated with the nextjs-auth0 package. Whenever I attempt to test a particular file and include the following import: import { getSession } from '@auth0/nextjs-auth0'; An error occurs, stating ...

Triggering an event from a component to its parent module resulting in an exception situation

Here is my app.component.ts code: import { Component, Input, OnInit, OnChanges, SimpleChanges} from '@angular/core'; import {Counter } from './counter' @Component({ selector: 'my-app', template: ` <custom-counter [ ...

A step-by-step guide on bundling a TypeScript Language Server Extensions LSP using WebPack

Currently, I am working on a language server extension for vs-code that is based on the lsp-sample code. You can find the code here: https://github.com/microsoft/vscode-extension-samples/tree/master/lsp-sample My challenge lies in WebPacking the extension ...

Retrieve the initial token from a union, referred to as an "or list," in Typescript

Is there a way to define a generic type F with the following behavior: type X = F<'a'|'b'|'c'> should result in X being 'a'. And if type X = F<'alpha'|'beta'|'gamma'|'del ...

Having trouble compiling the Electron App because of a parser error

Struggling to set up a basic electron app using Vue 3 and Typescript. Following the successful execution of certain commands: vue create app_name cd .\app_name\ vue add electron-builder npm run electron:serve Encountering issues when trying to i ...

Dynamically loading Angular modules based on API response is a powerful way to enhance

Can modules be lazily loaded in Angular without a static declaration in the RoutingModule? Right now, each module is declared in the RoutingModule. { path: 'path-one', loadChildren: () => import('./components/PathOne').then(m =&g ...

Is there a way to modify the style within a TS-File?

I've created a service to define different colors and now I want to set separate backgrounds for my columns. However, using the <th> tag doesn't work because both columns immediately get the same color. Here's my code: color-variatio ...

JavaScript alert box

I'm fairly new to the world of web development, with knowledge in CSS & HTML and currently learning TypeScript. I'm attempting to create a message icon that opens and closes a notifications bar. Here's where I'm at so far: document.getE ...

Rendering React component within a production build of Angular 7

I've been in the process of gradually moving an Angular app to React. After exploring options like single-spa and nx, I found that they weren't suitable due to the messy script-injected nature of the existing app. So, I decided to go for a semi-m ...

Sending data from view to controller in Angular using TypeScript

I am currently working with AngularJS and TypeScript, and I have encountered an issue with passing a parameter from the view to the controller. In my attempts to solve this problem, I have utilized ng-init as follows: <div class="col-md-9" ng-controlle ...

Guide on transforming a tuple of random types into a nested type structure with the help of recursive conditional types

When I responded to the query on whether Typescript Interfaces can express co-occurrence constraints for properties, I shared the following code snippet: type None<T> = {[K in keyof T]?: never} type EitherOrBoth<T1, T2> = T1 & None<T2&g ...