Angular 2+如何使用嵌套属性和非嵌套属性同时对数据数组进行排序?

时间:2017-12-11 10:00:28

标签: angular sorting nested

我有一个包含6列的表,其中包含来自根数组的数据:

  columns: any[] = [{ sortBy: 'startTime', title: 'Order Date' }, { sortBy: 'btcAmount', title: 'BTC' },
  { sortBy: 'btcPrice', title: 'Rate' }, { sortBy: 'total', title: 'Total' },
  { sortBy: 'status', title: 'Status' }, { sortBy: 'paymentResult.updated', title: 'Payment Date' }];

前5列能够正确排序,而按Payment Date排序的最后一列paymentResult.updated包含数据作为同一根数组(this.transactions)中的嵌套属性能够相应地排序。这是我的排序功能:

sort(property = 'startTime') {
    this.column = property;
    this.isDesc = !this.isDesc;
    this.direction = this.isDesc ? 1 : -1;
    this.transactions.sort((a, b) => {
      if (a === null) return -1;
      if (b === null) return 1;
      if (a[property] === b[property]) return 0;
      return a[property] < b[property] ? -1 * this.direction : 1 * this.direction;
    });
  } 

这是数组的数据结构:

{
  "id": "string",
  "status": "Open",
  "startTime": "2017-12-11T09:43:45.534Z",
  "validUntil": "2017-12-11T09:43:45.534Z",
  "btcAmount": 0,
  "btcPrice": 0,
  "total": 0,
  "paymentResult": {
    "id": "string",
    "status": "Paid",
    "updated": "2017-12-11T09:43:45.534Z"
  }      
}

这是观点:

<table class="table table-responsive table-hover" *ngIf="transactions" >
        <thead class="thead-default">
          <tr>
            <th *ngFor="let columnName of columns" 
                (click)="sort(columnName.sortBy)">
              {{columnName.title}}
            </th>
          </tr>
        </thead>
        <tbody>
          <tr *ngFor="let transaction of transactions>
            <td>{{ transaction.startTime | date: 'short' }}</td>
            <td>{{ transaction.btcAmount.toFixed(6) }}</td>
            <td>{{ transaction.btcPrice | currency:'USD':true }}</td>
            <td>{{ transaction.total | currency:'USD':true }}</td>
            <td>{{ transaction.status }}</td>
            <td> {{transaction.paymentResult?.updated}}</td>
          </tr>
        </tbody>
      </table>

1 个答案:

答案 0 :(得分:1)

有点这种我想 - 只是检查它是否是嵌套属性,如果是 - 逐个迭代属性直到找到值:

sort(property = 'startTime') {
    this.column = property;
    this.isDesc = !this.isDesc;
    this.direction = this.isDesc ? 1 : -1;
    this.transactions.sort((a, b) => {
    let a1 = a;
    let b1 = b;
    if(property.indexOf('.') > -1) {
     let keys = property.split('.');
     keys.forEach((key) => {
       if(a1 == null) return -1;
       if (b1 === null) return 1;
       a1 = a1[key];
       b1 = b1[key];
     })
    }
      if (a === null) return -1;
      if (b === null) return 1;
      if (a1 === b1) return 0;
      return a[property] < b[property] ? -1 * this.direction : 1 * this.direction;
    });
  } 

未经测试,但这个想法很明确。