我有一个这样的结构,需要按 Locations.Address.distance 排序
{
"Id": "123",
"Type": "someType",
"Locations": [{
"Address": {
"Line1": "111 test dr",
"City": "pope",
"State": "AZ",
"PostalCode": {
"Part1": "87212"
}
},
"Distance": "0.7" }]
},
{
"Id": "456",
"Type": "someType",
"Locations": [{
"Address": {
"Line1": "777 test dr",
"City": "pope",
"State": "AZ",
"PostalCode": {
"Part1": "87212"
}
},
"Distance": "0.1" }]
}
位置数组将始终只有一项。我想进行排序,使 id= 456 的第二个对象显示为第一个元素,因为它的距离 = 0.1,小于距离 = 0.7 的第一个元素的距离。我尝试过类似的方法,但它不起作用:
sortedList =filter('orderBy')($scope.responseArray,'Locations.this[0].Distance'], false);
最佳答案
通过使用过滤器,你会喜欢下面的内容
var result=$filter('orderBy')(this.items, 'Locations[0].Distance')
https://stackblitz.com/edit/js-sort-complex-array?file=index.js
另一种方法是使用 javascript sort() 方法,您可以编写自己的排序逻辑
var result = items.sort(function (a, b) {
var distance1 = parseFloat(a.Locations[0].Distance);
var distance2 = parseFloat(b.Locations[0].Distance);
if (distance1 < distance2) {
return -1;
}
if (distance1 > distance2) {
return 1;
}
return 0;
});
工作演示
https://stackblitz.com/edit/angularjs-complex-filter?file=home/home.controller.js
关于javascript - ng-repeat 对内部包含数组的复杂对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53123466/