Home > Blockchain >  Displaying keys and values from a list of object in angular typescript
Displaying keys and values from a list of object in angular typescript

Time:09-29

In my angular app, I have a list of objects that I get dynamically from an API that looks for example like this :

[
    {
        "_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 want to be able to access the key and values of each object without mentioning them explicitly, this way if I get a list with more objects or different keys I would be able to display them as well, How can I do that ?

<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);
    });

CodePudding user response:

You could use the Angular keyvalue pipe to traverse each property of the object. Try the following

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'.
  • Related