javascript - ng-repeat 对其中包含数组的复杂对象进行排序
问题描述
我有这样的结构,需要按 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" }]
}
Locations 数组将始终只有 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
推荐阅读
- symfony - Symfony FormLoginAuthenticator 不登录用户
- python - 如何从 python 中的字典列表中的项目中删除部分字符串和 None 值?
- javascript - 添加比例会导致画布元素失真
- python - 在字典列表中查找值
- javascript - 使 bootstrapvalidator 无效以避免一次又一次提交相同的数据
- sql - 尝试创建新表(datagrip)时出现此错误
- plc - 如何在 Twincat 3 上的一个项目中创建两个 plc 项目
- java - 无法在 Micronaut 中注入具有命名限定符的不同 bean
- rbac - Casbin:如何实现模型和策略
- java - 将布尔值从 UI 传递到休息控制器