我正在尝试对数组列表进行排序,但无济于事。
问题:我有一个对象列表,但是我需要通过一个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或循环?
答案 0 :(得分:2)
如果您需要使用序列数组的给定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; }

答案 1 :(得分:1)
使用ng-repeat
排序非常简单
<div data-ng-repeat="item in items | orderBy: 'id' ">
答案 2 :(得分:0)
您可以使用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)
答案 3 :(得分:0)
您可以使用原生sort方法并使用比较功能,如下所示:
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
。
答案 4 :(得分:0)
有几种方法可以做到这一点。 1.您可以在控制器中编写一个排序函数,在调用api之后对返回对象进行排序,并将其放入变量中,以便在排序后以角度为单位进行引用。 你可以使用这样的东西:orderBy array item value in Angular ng-repeat对ng重复。