首页 > 解决方案 > 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);

标签: javascriptangularjs

解决方案


通过使用过滤器,您可以执行以下操作

 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


推荐阅读