如何用角度对1月到12月的月份列表进行排序?

问题描述 投票:1回答:2

浏览器默认情况下按字母顺序对月份列表进行排序。如何按月份顺序对其进行排序?这是.ts文件中的对象数据:

 objdata:{ '2017': 
   { total: 150000,
     data: 
      { January: 1200,
        February: 1200,
        March: 1300,
        April: 1300,
        May: 1200,
        June: 2000,
        July: 5000,
        August: 4000,
        September: 4500,
        October: 1200,
        November: 9000,
        December: 9000 } },
  '2018': 
   { total: 20000,
     data: 
      { January: 1200,
        February: 1200,
        March: 1300,
        April: 1300,
        May: 1200,
        June: 2000,
        July: 5000,
        August: 4000,
        September: 4500,
        October: 1200,
        November: 9000,
        December: 9000 } }
}

我正在使用* ngFor来显示数据:

 <tr *ngFor="let item of objdata | keyvalue">
      <td scope="row">
        <mat-accordion>
          <mat-expansion-panel>
            <mat-expansion-panel-header>
              <mat-panel-title>
                Year {{item.key}}
              </mat-panel-title>
              <mat-panel-description> 
                  {{item.value['total']}}
              </mat-panel-description>
            </mat-expansion-panel-header>
            <div class="row" *ngFor="let subitem of item.value['data'] | keyvalue">
              <label class="col-sm-3 col-form-label">{{subitem.key | titlecase}}</label>
              <label class="col-sm-9 col-form-label">{{subitem.value}}</label>
            </div>
          </mat-expansion-panel>
        </mat-accordion>
      </td>
    </tr>

我如何像一月,二月,三月......这样排序?

javascript angular sorting angular-material angular7
2个回答
2
投票

Working Demo

您可以像这样创建pipe

import { Pipe, PipeTransform } from "@angular/core";

@Pipe({
  name: "sortMonth"
})
export class SortMonthPipe implements PipeTransform {
  transform(value: any, args?: any): any {
    console.log(value);
    var months = [
      "January",
      "February",
      "March",
      "April",
      "May",
      "June",
      "July",
      "August",
      "September",
      "October",
      "November",
      "December"
    ];
    value.sort(function(a, b) {
      return (
        months.indexOf(a.key) -
        months.indexOf(b.key)
      );
    });
    return value;
  }
}

。html

<div class="row" *ngFor="let subitem of item.value['data'] | keyvalue | sortMonth">
     <label class="col-sm-3 col-form-label">{{subitem.key | titlecase}}</label>
     <label class="col-sm-9 col-form-label">{{subitem.value}}</label>
</div>

0
投票

另一个方法是获得一组有序的键。您的情况可以像

this.orderKeys=JSON.stringify(this.objdata[Object.keys(this.objdata)[0]].data)
       .replace(/((:\b(\w*\w*)\b)|{|}|\")/g,"").split(',')
© www.soinside.com 2019 - 2024. All rights reserved.