[英]Move an element at the beginning of an array of objects
我有這樣的數組格式
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 }] }] } ], }
並且所需的格式是
{ "data": [ { "district": "sikkim district", "food saftey": 2, "food ": 2, "air pollution": 0 }, { "district": "Bhojpur", "food saftey": 1, "food ": 1, "air pollution": 1 }, ], }
數組格式是動態的,除了分區外一直在變化,分區必須在數組的開頭。
您可以做的是將您知道的屬性首先放在列數組中,然后獲取其他屬性並使用列數組中的順序進行循環。
像這樣的東西:
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>
注意:我將您的數據更改為有效的 json。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.