将元素移到对象数组的开头

时间:2019-01-17 08:34:51

标签: javascript typescript

我有这样的数组格式

snapshot

,所需格式为

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
        }]
      }]
    }
  ],

}

数组格式是动态的,除了区域之外,其他格式一直在变化 并且区必须在数组的开头。

1 个答案:

答案 0 :(得分:1)

您可以做的是先将您知道的属性放在列数组中,然后获取其他属性,然后使用列数组中的顺序进行遍历。

类似这样的东西:

Stackblitz

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。