Converting an object to an array
dataSource = [];
var data = {
cars: 24,
fruit: "apple",
phone: "Iphone",
food: "Burger"
};
for (const key in data) {
dataSource.push({ key, value: data[key] });
}
and utilizing it with Angular Material
.ts file
import { Component } from "@angular/core";
export interface RowElement {
key: string;
value: string;
}
@Component({
selector: "table-basic-example",
styleUrls: ["table-basic-example.css"],
templateUrl: "table-basic-example.html"
})
export class TableBasicExample {
data = {
cars: 24,
fruit: "apple",
phone: "Iphone",
food: "Burger"
};
displayedColumns: string[] = ["key", "value"];
dataSource: RowElement[];
constructor() {
for (const key in this.data) {
this.dataSource.push({ key, value: this.data[key] });
}
}
}
.html file
<table mat-table [dataSource]="dataSource">
<!-- Key Column -->
<ng-container matColumnDef="key">
<th mat-header-cell *matHeaderCellDef>Key</th>
<td mat-cell *matCellDef="let element">{{element.key}}</td>
</ng-container>
<!-- Value Column -->
<ng-container matColumnDef="value">
<th mat-header-cell *matHeaderCellDef>Value</th>
<td mat-cell *matCellDef="let element">{{element.value}}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>