【问题标题】:How to custom sort JSON array in Typescript or Angular如何在 Typescript 或 Angular 中自定义排序 JSON 数组
【发布时间】:2018-07-08 23:17:52
【问题描述】:

如何在 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 条件时,先打印 所以它就像 JSON 11,2,6,3,15,1,9

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

【问题讨论】:

  • 你会将它放在哪个排序逻辑中?
  • 你可以在实现视图之前自定义排序你的数组吗?
  • Array.prototype.sort?
  • 任何方法都可以,是否可以在ngFor div..中排序?

标签: angular sorting typescript ng-switch


【解决方案1】:

只需使用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

【讨论】:

  • 简单而干净的解决方案,谢谢,是否可以从 Angular 中的视图侧执行..?
  • @Mrworldwide :您可以创建自定义管道进行排序
猜你喜欢
  • 2020-02-27
  • 1970-01-01
  • 2021-09-16
  • 1970-01-01
  • 2017-05-02
  • 2016-12-25
  • 2020-05-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多