![](/img/trans.png)
[英]How do I sort an array of objects by id when the id has letters at the beginning?
[英]How do I sort my list of objects by an id array in angularjs?
我正在嘗試對數組列表進行排序,但無濟於事。
問題 :我有一個對象列表,但我需要通過id字符串對其進行排序,該字符串位於數組中。
JSON:
[{"id":2613,"name":"Aula 01","section":989},{"id":2614,"name":"Aula 02","section":989},{"id":2616,"name":"Aula 04","section":989},{"id":2617,"name":"Aula 05","section":989,},{"id":2615,"name":"3 - Aula 03","section":989}]
數組ID序列:
["2613", "2614", "2615", "2616", "2617"]
如何在這個數組中命令ng-repeat或循環?
如果您需要使用序列數組的給定id
的任意順序,則可以使用具有排序順序的對象。
array = [{ id: 2613, name: "Aula 01", section: 989 }, { id: 2614, name: "Aula 02", section: 989 }, { id: 2616, name: "Aula 04", section: 989 }, { id: 2617, name: "Aula 05", section: 989 }, { id: 2615, name: "3 - Aula 03", section: 989 }], sequence = ["2617", "2613", "2614", "2615", "2616"], order = {}; sequence.forEach(function (id, i) { order[id] = i + 1 }); array.sort(function (a, b) { return order[a.id] - order[b.id]; }); console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
使用ng-repeat
排序非常簡單
<div data-ng-repeat="item in items | orderBy: 'id' ">
你可以使用js這樣排序a.id-b.id
var arr =[{"id":2613,"name":"Aula 01","section":989},{"id":2614,"name":"Aula 02","section":989},{"id":2616,"name":"Aula 04","section":989},{"id":2617,"name":"Aula 05","section":989,},{"id":2615,"name":"3 - Aula 03","section":989}] var res = arr.sort((a,b)=> a.id-b.id) console.log(res)
您可以使用本機排序方法並使用比較函數,如下所示:
var json = [{"id":2613,"name":"Aula 01","section":989},{"id":2614,"name":"Aula 02","section":989},{"id":2616,"name":"Aula 04","section":989},{"id":2617,"name":"Aula 05","section":989,},{"id":2615,"name":"3 - Aula 03","section":989}];
var result = json.sort((a, b) => a.id - b.id)
console.log(result);
假設您的JSON來自服務,它可能如下所示:
$scope.json = service.getJson().sort((a, b) => a.id - b.id);
或者可能:
service.getJson().then(function (data) {
$scope.json = data.sort((a, b) => a.id - b.id);
});
然后你可以在視圖中ng-repeat
它。
有幾種方法可以做到這一點。 1.您可以在控制器中編寫一個排序函數,在調用api之后對返回對象進行排序,並將其放入變量中,以便在排序后以角度為單位進行引用。 2.你可以使用這樣的東西:在ng重復的Angular ng-repeat中的orderBy數組項值 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.