I have a below response from HTTP
getEmployee(id: number){
this.empservice.getEmployee(id)
.subscribe({
next:(res)=>{
this.obj = res;
},
error:(err)=>{
alert("Error getting the employee");
console.warn(err);
}
})
}
I want to iterate the response in to a HTML Table or MAT table.
<table mat-table [dataSource]="obj">
<tbody>
<tr data-ng-repeat="(key, val) in obj[0]">
<th>
{{ key }}
</th>
<td data-ng-repeat="row in obj">
{{ rowSource[key] }}
</td>
</tr>
</tbody>
</table>
Below is the response object that i get from API
{
"employeeID": 999,
"firstName": "Peter",
"lastName": "Scotch",
"phone": "8878767654",
"email": "[email protected]",
}
CodePudding user response:
you can use a plain for (x in obj) { } loop:
const user = {
"employeeID": 999,
"firstName": "Peter",
"lastName": "Scotch",
"phone": "8878767654",
"email": "[email protected]",
}
for (let key in user) {
if (user.hasOwnProperty(key)) {
console.log(key " : " user[key]);
}
}
CodePudding user response:
const testObj = {
"employeeID": 999,
"firstName": "Peter",
"lastName": "Scotch",
"phone": "8878767654",
"email": "[email protected]",
};
// 1 way
Object.entries(testObj).forEach(x => {
let key = x[0]
let value = x[1];
})
// 2 way
Object.keys(testObj).forEach(key => {
let value = testObj[key];
})
If you want to iterate it in html-table, try:
<table>
<thead>
<tr>
<th>Key</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let key of Object.keys(obj)">
<td>{{key}}</td>
<td>{{obj[key]}}</td>
</tr>
</tbody>
</table>