如何在Typescript或Angular中自定义排序JSON数组



如何在Angular中对JSON数组进行排序?数组:

{"title":"DEASDFS","Id":11},
{"title":"AASDBSC","Id":2},
{"title":"JDADKL","Id":6},
{"title":"MDASDNO","Id":3},
{"title":"GHFASDI","Id":15},
{"title":"HASDFAI","Id":1},
{"title":"ASDHFI","Id":9},

我想要 ID 的顺序是这样的:

15,6,1,11,9,2,3

<div *ngFor="let field of fieldsData;let i=index;">
  <div class="form-inline assigned_text-box" [ngSwitch]="field.Id">
    <div class="col-md-2" *ngSwitchCase="15">
      <label>One</label>
    </div>
    <div class="col-md-2" *ngSwitchCase="6">
      <label>Two</label>
    </div>
    <div class="col-md-2" *ngSwitchCase="1">
      <label>Three</label>
    </div>
    <div class="col-md-2" *ngSwitchCase="11">
      <label>Four</label>
    </div>
    <div class="col-md-2" *ngSwitchCase="9">
      <label>Five</label>
    </div>
    <div class="col-md-2" *ngSwitchCase="2">
      <label>Six</label>
    </div>
    <div class="col-md-2" *ngSwitchCase="3">
      <label>Seven</label>
    </div>
  </div>
</div>

但是当我使用ngSwitch条件时,n 哪个先出现,那就是打印所以它就像 JSON 11、2、6、3、15、1,9 中一样

但我想要这个订单 15,6,1,11,9,2,3。如何实现此自定义排序数组?

只需使用Array#sort方法对数组进行排序。

// reference for sort order priority
const ref = {
  15: 0,
  6: 1,
  1: 2,
  11: 3,
  9: 4,
  2: 5,
  3: 6
};
let data = [{
    "title": "DEASDFS",
    "Id": 11
  },
  {
    "title": "AASDBSC",
    "Id": 2
  },
  {
    "title": "JDADKL",
    "Id": 6
  },
  {
    "title": "MDASDNO",
    "Id": 3
  },
  {
    "title": "GHFASDI",
    "Id": 15
  },
  {
    "title": "HASDFAI",
    "Id": 1
  },
  {
    "title": "ASDHFI",
    "Id": 9
  },
];
console.log(
  data.sort((a, b) => ref[a.Id] - ref[b.Id])
)


或实现自定义管道进行排序:Angular 2 OrderBy Pipe

相关内容

  • 没有找到相关文章

最新更新