Is it possible to create a dynamic Table(dynamic Columns) based on a JSON object with Angular 5? If so how?
I get the following json as response of API:
{
"ResponseStatus": true,
"ResponseData": [
{
"Parent": "Company 1",
"Data": [
{
"Field1": "Membership 1",
"Field2": "153.00"
},
{
"Field1": "Membership 2",
"Field2": "130.00"
},
{
"Field1": "Membership 3",
"Field2": "1850.00"
}
]
},
{
"Parent": "Company 2",
"Data": [
{
"Field1": "Membership 1",
"Field2": "148.00"
},
{
"Field1": "Membership 2",
"Field2": "100.00"
},
{
"Field1": "Membership 4",
"Field2": "1800.00"
}
]
}
]
}
Now I want to create table based on this data that should be:
+------------------+------------------+------------------+
| Membership Type | Company 1 | Company 2 |
+------------------+------------------+------------------+
| Membership 1 | 153.00 | 148.00 |
+------------------+------------------+------------------+
| Membership 2 | 130.00 | 100.00 |
+------------------+------------------+------------------+
| Membership 3 | 1850.00 | |
+------------------+------------------+------------------+
| Membership 4 | | 1800.00 |
+------------------+------------------+------------------+
NOTE: Number of company could be different.
What would the best approach be to solve this? I just cant figure it out how to solve this problem? Any help is really appreciated.
Here I play with some code as:
ngOnInit() {
this.headers = this.Testdata.map(t => t.Parent);
this.Testdata.forEach(x => {
x.Data.forEach(y => y['Parent'] = x.Parent)
})
var data = this.Testdata.map(t => t.Data);
var temp = [];
data.forEach(function(a) {
temp.push(a.map(function (t) {
let c = {};
c['Field1'] = t.Field1;
c[t['Parent']] = t.Field2;
return c;
}));
});
var rowList = temp.flat();
}
<table>
<thead>
<tr>
<td *ngFor="let col of headers">{{col}}</td>
</tr>
</thead>
<tbody>
<tr *ngFor="let row of rowData">
<td>{{row.Field1}}</td>
<td *ngFor="let col of headers">
{{row[col]}}
</td>
</tr>
</tbody>
</table>