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