我收到的数据对象已被透视,并且无法更改返回给我的结构。在这一点上,我唯一的选择是操纵数据以按需要解析它。

这是我的结果:

  // Object from service
  let dataObj = [{
    CostCenter: '12345',
    HasLevel1Access: 'No',
    HasLevel2Access: 'No',
    HasLevel3Access: 'Yes',
    FirstName: 'Bob',
    LastName: 'Jones',
    UID: '12345'
  },
  {
    CostCenter: '555',
    HasLevel1Access: 'Yes',
    HasLevel2Access: 'No',
    HasLevel3Access: 'Yes',
    FirstName: 'Tommy',
    LastName: 'C',
    UID: '6789'
  },
  {
    CostCenter: '51112',
    HasLevel1Access: 'Yes',
    HasLevel2Access: 'No',
    HasLevel3Access: 'Yes',
    FirstName: 'Smithson',
    LastName: 'J',
    UID: '8888'
  }];


根据这些数据,我需要制作一张桌子。这里的技巧是,我需要使用某些属性名称作为列标题,而排除其他属性。

我的表非常基本,它包含人员名称,然后是所有动态列名称:

<table class="table table-condensed" border="1">
      <thead>
        <tr>
          <th>Employee Name</th>
          <th *ngFor="let m of columnNames">{{ m }}</th>
        </tr>
      </thead>
      <tbody>
        <!-- Example Record 0 -->
        <tr>
          <td>Bob Jones</td>
          <td>No</td>
          <td>No</td>
          <td>Yes</td>
        </tr>
        <!-- Example Record 0 -->
      </tbody>
    </table>


为了获取列名,我要做的第一件事是创建一个IgnoreColumns数组,这是我不想从表中自己的列中排除的属性名。

// Hold all of the column names
private columnNames = [];

// Ignore these columns, they dont get printed as headers
private ignoreColumns = ['CostCenter', 'FirstName', 'LastName', 'UID'];


然后,我遍历结果集中的第一条记录,并将所有属性名称推送到不在我们的ignoreColumns数组中的数组。这给我留下了动态列的唯一数组。

// Find all the keys in our first result
for (var p in dataObj[0]) {

  // Get the key names
  if (dataObj[0].hasOwnProperty(p)) {

    // If this key name doesnt already exist in the array AND its not in our ignored list push them to our array
    if (!_.includes(this.columnNames, p) && !_.includes(this.ignoreColumns, p)) {
      this.columnNames.push(p);
    }

  }

}


我被困在这一点上。我能够使用标题创建表结构,但是我不知道如何继续将数据对齐到表中正确的列下。

这是我在最终输出中要执行的操作:

<table class="table table-condensed" border="1">
    <thead>
    <tr>
        <th>Individual</th>
        <th>HasLevel1Access</th>
        <th>HasLevel2Access</th>
        <th>HasLevel3Access</th>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td>Bob Jones</td>
        <td>No</td>
        <td>No</td>
        <td>Yes</td>
    </tr>
    <tr>
        <td>Tommy C</td>
        <td>Yes</td>
        <td>No</td>
        <td>Yes</td>
    </tr>
    <tr>
        <td>Smithson J</td>
        <td>Yes</td>
        <td>No</td>
        <td>Yes</td>
    </tr>
    </tbody>
</table>


这是我所在的地方:http://plnkr.co/edit/9WygBXsQaDaxTMudb7ZB?p=preview

有关如何处理此问题的任何建议?

最佳答案

关于什么

      <tr *ngFor="let item of dataObj">
          <td>{{item.FirstName}} {{item.LastName}}</td>
          <td *ngFor="let m of columnNames">{{item[m]}}</td>
        </tr>


Working demo

10-04 15:58
查看更多