如何在 Typescript 或 Angular 中自定义排序 JSON 数组
How to custom sort JSON array in Typescript or Angular
如何对 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
如何对 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