Showing key-value pairs from an array of objects using Angular TypeScript

Within my angular application, I am fetching a dynamic list of objects from an API. A sample of the data structure is as follows:

[
    {
        "_id": "some id",
        "DATE": "2021/01/08",
        "COUNT": "23",
        "AMOUNT": "268710"
    },
    {
        "_id": "some id",
        "DATE": "2021/09/18",
        "COUNT": "2",
        "AMOUNT": "1,167.73"
    }
]

I am looking for a way to dynamically access the keys and values of each object without explicitly specifying them. This will allow me to display any additional objects with different keys that may be retrieved in the future. Can someone guide me on achieving this?

<tr
                  *ngFor="
                    let row of FilteredMatchTransactions
                      | paginate
                        : { itemsPerPage: itemsPerPage, currentPage: p };
                    let i = index
                  "
                >
                  <td>
                    {{ KeysFilteredMatchTransactions[1] }} :
                    {{ row.DATE}}
                  </td>
                  <td>
                    {{ KeysFilteredMatchTransactions[2] }} : {{ row.COUNT}}
                  </td>
                  <td>
                    {{ KeysFilteredMatchTransactions[3] }} :
                    {{ row.AMOUNT}}
                  </td>
                </tr>

TS :

ngOnInit(): void {
    const Param = this.route.snapshot.queryParamMap.get('_id');
    this._crudService.GetReportById(Param).subscribe((res) => {
      this.MatchTransactions = res;
      this.FilteredMatchTransactions = this.MatchTransactions.onlyInFile1;

      this.KeysFilteredMatchTransactions = Object.keys(
        this.FilteredMatchTransactions[0]
      );
      console.log(this.KeysFilteredMatchTransactions);
    });

Answer №1

To iterate through each property of an object in Angular, you can utilize the keyvalue pipe. Give this a try:

Controller (*.ts)

ngOnInit(): void {  
  const Param = this.route.snapshot.queryParamMap.get('_id');
  this._crudService.GetReportById(Param).subscribe((res) => {
    this.MatchTransactions = res;
    this.FilteredMatchTransactions = this.MatchTransactions.onlyInFile1;
  });
}

Template (*.html)

<tr 
  *ngFor="let row of FilteredMatchTransactions | 
          paginate : { itemsPerPage: itemsPerPage, currentPage: p };
          let i = index"
>
  <ng-container *ngFor="let transaction of row | keyvalue">
    <td *ngIf="transaction.key !== '_id'">
      {{ transaction.key }} : {{ transaction.value }}
    </td>
  </ng-container>
</tr>

Update:

  1. FilteredMatchTransactions -> row in 2nd *ngFor.
  2. *ngIf check for key !== '_id'.

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

Revamp your arrays with input fields in Vue3

When presented with two arrays of options, users must select an option from each array. ==> first array: [ orange, green, yellow ] ==> second array: [ orange, green, yellow ] The challenge is to update the second array based on the user's sele ...

Upgrading an Angular 1 directive to Angular 4

I have created a custom directive in Angular 1 that allows drag and drop functionality for images in a web application. Here is the original code: 'use strict'; angular.module('abc').directive("imageFileRead", ['$document', ...

Looking to integrate a widget into the pages of an Ionic 3 app?

I need to incorporate an external widget into my Ionic application. It's functioning properly when I add the script to my index.html and use the widget HTML element on the initial loading page (e.g. Home.html), but it isn't working on other pages ...

What could be causing the express middleware function to break only under specific conditions when the 4th argument is included?

As a newcomer to node/express, I encountered a peculiar situation. When I add a 4th "value" parameter to certain middleware functions, they fail to work while others function properly. I have come across information suggesting that adding a 4th parameter c ...

Switch Angular checkbox to display string values instead of boolean true/false

My task is to create three checkboxes in a form with values toggling between "optin" and "optout" as I check/uncheck the checkboxes. Additionally, all checkboxes should be checked by default for the "optin" value. I'm struggling to find a solution, an ...

Display a specific template in the detail grid of the Kendo Grid depending on certain conditions

I've been using the Kendo Grid and it's been working well for me. I have a requirement to check each row in my grid to see if it contains a specific value, and based on that, bind data using different templates. Is this feasible? Below is the cod ...

Utilize d3.behavior.zoom to target and zoom in on a particular group ID, while also retrieving the bounding box

I'm currently working on creating an interactive pan/zoom SVG floorplan/map by utilizing the d3.behavior.zoom() feature. My code is inspired by the concept of Zoom to Bounding Box II. My approach involves asynchronously loading an SVG using $.get() a ...

How can one create a function that delays the execution of code until AJAX data is received

I developed a CKEditor plugin that fetches data via ajax to create RichCombo functionality. The plugin functions correctly, however, when there are multiple instances of the editor on a single page, each plugin ends up sending its own ajax request, leading ...

A guide on incorporating Vue.js into a Hexo static site generator

Exploring the use of vue.js within my hexo theme has sparked my interest. Can anyone guide me on how to compile my .vue files for both development and production environments? It's worth mentioning that I intend for vue.js to operate on the client sid ...

php generate a new file within a specific folder

In the following code snippet, a check is performed for the existence of a directory named 'dat'. If the directory does not exist, it is created. This functionality works correctly; however, the goal is to write a file to this directory that can ...

Arrange the select default option using AngularJS as the first option

I've been working on a project using Angular where I fetch data from a JSON file and push it to an array object. This data is then displayed in the options of a select element. My issue is: The default option with selection appears first, but I only ...

Steps to activate the parent list item when the child item is altered

As a newcomer to both ui router and angularjs, I'm encountering a specific issue: Within my header section, the following code is present: <li ng-class="{active: $state.includes('settings')}" id="header01"> <a ...

How can you retrieve a value in NodeJS Promise (Q) even when the promise fails?

As I dive into the world of promises in my NodeJS projects, I encountered a challenging situation. Despite reading the Promises/A+ spec and conducting extensive searches online, I struggled to find an elegant solution for accessing a value generated within ...

Tips for sending parameters in Next.js without server-side rendering

I followed the documentation and tried to pass params as instructed here: https://nextjs.org/docs/routing/dynamic-routes However, I encountered a strange issue where the received params are not in string format. How is it possible for them to be in an arr ...

What is the best way to prevent the dropdown function in a selectpicker (Bootstrap-Select)?

Is there a way to completely disable a selectpicker when a radio button is set to "No"? The current code I have only partially disables the selectpicker: $("#mySelect").prop("disabled", true); $(".selectpicker[data-id='mySelect']").addClas ...

How to override or redefine a TypeScript class with generics

Presently, I am immersed in a project involving three.js and TypeScript. It has come to my attention that for organizing elements, the Group class is highly recommended. However, I have noticed that the type definitions for Group do not include a feature l ...

Cookies are swiftly dispatched with headers and securely stored, only to disappear upon reloading

I have extensively researched various topics related to this issue, but I still haven't been able to resolve the problem. The Set-Cookie is present in the response headers as shown below, albeit with a minor warning. Since I am using HTTP, I am requir ...

Is there a way for me to produce a random choice depending on the option selected by the user in the <select> menu?

As a beginner in JavaScript, I am attempting to create a feature where users can select a genre from a dropdown list and receive a random recommendation from that genre displayed on the screen. In essence, my goal is to allow users to get a random suggest ...

Error message: The variable GLOBAL is not defined in the fetch-mock code

I am currently using fetch-mock to write unit tests for functions that utilize isomorphic-fetch. Below is a sample of the test suite I have created: import connect from '../../src/utils/connect'; import fetchMock from 'fetch-mock'; ...

The function that iterates through the 'categoria' state and returns a new array is not functioning properly

Having difficulty with the object of a function using .map(). It works when the code is used directly, but not when put inside a function. For example: if(this.state.cat){ return _.map(this.state.cat, categoria => { if(this.state.search_ ...