Warm tip: This article is reproduced from serverfault.com, please click

How to to display array of objects of array in *ngfor

发布于 2020-11-28 08:44:53

I have an array like this

 tdata = {
    jam: [1, 2, 4, 5],
    ram: [11, 12, 34, 14],
    sam: [21, 22, 23, 24],
    jug: ["a", "b", "c", "d"],
    tam: [31, 32, 33, 34]
  };

` I want to print/display object keys like jam, ram, sam as table headers and their values in the respective table in angular with Pprimeng table. I tried various ways but unable to display correctly. Primeng table for dynamic values

<p-table [columns]="cols" [value]="products">
    <ng-template pTemplate="header" let-columns>
        <tr>
            <th *ngFor="let col of columns">
                {{col.header}}
            </th>
        </tr>
    </ng-template>
    <ng-template pTemplate="body" let-rowData let-columns="columns">
        <tr>
            <td *ngFor="let col of columns">
                {{rowData[col.field]}}
            </td>
        </tr>
    </ng-template>
</p-table>

If I want to display I need the array to be automatically in the form

tdata = [
        {jam:1,ram:11,sam:21,jug:"a",tam:31},
        {jam:2,ram:12,sam:22,jug:"b",tam:32},
        {jam:3,ram:34,sam:23,jug:"c",tam:33},
        {jam:5,ram:14,sam:24,jug:"d",tam:34 }
      ]

Values In the tdata may change dynamically they come from the backend and key also

Questioner
bhavya
Viewed
0
IRSHAD 2020-11-28 17:07:47

Get the length of array first. Then iterate over the Object.keys to get values of each key to get the new row.

tdata = {
    jam: [1, 2, 4, 5],
    ram: [11, 12, 34, 14],
    sam: [21, 22, 23, 24],
    jug: ["a", "b", "c", "d"],
    tam: [31, 32, 33, 34]
};

let tdataFormatted = [];
let rowLength = Object.keys(tdata)[0].length; //get the length of the first property.

let i = 0;
while (i < rowLength) {

    let newObj = {};

    for (key in tdata) {
        newObj[key] = tdata[key][i];
    }

    tdataFormatted.push(newObj)

    i++;
}

console.log(tdataFormatted);