Reputation: 423
I have array format like this
response = {
"data": [{
"districts": [{
"id": 1,
"name": "sikkim district",
"statistics": [{
"food saftey": 2,
"food ": 2,
"air pollution": 0
}]
}]
},
{
"districts": [{
"id": 2,
"name": "Bhojpur",
"statistics": [{
"food saftey": 1,
"food ": 1,
"air pollution": 1
}]
}]
}
],
}
and the required format is
{
"data": [
{
"district": "sikkim district",
"food saftey": 2,
"food ": 2,
"air pollution": 0
},
{
"district": "Bhojpur",
"food saftey": 1,
"food ": 1,
"air pollution": 1
},
],
}
The array format is in dynamic which keeps changing except the district and the district has to be at the beginning of the array.
Upvotes: 1
Views: 65
Reputation: 1673
What you can do is put the property you know first in a column array and then get the other properties and loop over using the order in the column array.
Something like this:
import {
Component
} from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
data = [{
"Bal Vivah": 1,
"Type": 0,
"districts": "East District"
},
{
"Bal Vivah": 1,
"Type": 0,
"districts": "West District"
},
{
"Bal Vivah": 1,
"Type": 0,
"districts": "North District"
}
]
columns: string[] = ["districts"];
constructor() {
// get the columns from the data
if (this.data) {
var dataObject = this.data[0];
for (var property in dataObject) {
if (property != "districts" && dataObject.hasOwnProperty(property)) {
this.columns.push(property);
}
}
}
}
}
<table>
<thead>
<tr *ngFor="let column of columns">
<th>{{column}}</th>
</tr>
</thead>
<tbody>
<ng-container *ngFor="let columnData of data">
<tr *ngFor="let column of columns">
<td>
{{columnData[column]| json}}
</td>
</tr>
</ng-container>
</tbody>
</table>
Note: I changed your data to be valid json.
Upvotes: 1