Angular.js通过2个给定属性搜索数组中的匹配对象

时间:2017-02-08 12:20:41

标签: angularjs indexof

我有一张CItyDistance表:CIty1Id | City2Id | Distance(KM), 现在在我的项目中我收到2个城市的ID,我想检查这2个城市是否有计算距离。

所以无论是City1还是City2都没关系,我需要检查这两个选项。 我发现检查它的方式太长而且凌乱。 有人可以提供另类选择吗? (请检查Plunker示例:https://plnkr.co/edit/nzB8zy0034LqJFgL8qk7?p=preview

 $scope.CompanyCity = { Id: 59, Name: 'berline' };

 $scope.result = "";

 $scope.distances = [ 
 {city1: 59,city2: 1,  Distance: 50 }, 
 {city1: 1, city2: 58, Distance: 80 },
 {city1: 3, city2: 59, Distance: 25 },
 {city1: 4, city2: 1,  Distance: 120 }];


 $scope.findDistance = function(studentCityID) {
    angular.forEach($scope.distances, function(value, key) {
        if (value.city1 == studentCityID && value.city2 == $scope.CompanyCity.Id) {
            $scope.result = value.Distance;
        } 
        else if (value.city2 == studentCityID && value.city1 == $scope.CompanyCity.Id) {
            $scope.result = value.Distance;
        }
    });
};
$scope.findDistance(1); 

3 个答案:

答案 0 :(得分:2)

您可以尝试此操作,用此替换$scope.findDistance功能。我认为它有更少的代码和有效的方法来实现您的要求。

 $scope.findDistance = function(studentCityID) {
    angular.forEach($scope.distances, function(value, key) {
        var arr = Object.values(value);
        if(arr.indexOf(studentCityID) !== -1 && arr.indexOf($scope.CompanyCity.Id) !== -1) {
               $scope.result = value.Distance;
        }
    });
};

添加了plunker,https://plnkr.co/edit/3r3intufeiqc26kzcnca?p=preview

谢谢,祝你好运:)

答案 1 :(得分:0)

我认为由于json结构,你实现的很好。我只能建议下面的代码

$scope.findDistance = function(studentCityID) {
    for (var count=0; count<$scope.distances.length; count++) {
      if (($scope.distances[count].city1 == studentCityID && $scope.distances[count].city2 == $scope.CompanyCity.Id) || 
          ($scope.distances[count].city2 == studentCityID && $scope.distances[count].city1 == $scope.CompanyCity.Id)) {
          $scope.result = $scope.distances[count].Distance;
          break;
      }
    }
};

请告诉我它是否有帮助!

答案 2 :(得分:0)

使用以下方法&amp;运算符以优化您的代码:

  • 使用Array filter()方法迭代数组并创建一个新数组,其中包含通过所提供函数实现的测试的所有元素。
  • 使用JavaScript ternary operator此运算符经常用作if语句的快捷方式。

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl',function($scope) {

$scope.CompanyCity = { Id: 59, Name: 'berline' };

$scope.distances = [ 
  {city1: 59,city2: 1,  Distance: 50 }, 
  {city1: 1, city2: 58, Distance: 80 },
  {city1: 3, city2: 59, Distance: 25 },
  {city1: 4, city2: 1,  Distance: 120 }
];


$scope.findDistance = function(studentCityID) {
    var res = $scope.distances.filter(function(item) {
        return (item.city1 == studentCityID && item.city2 == $scope.CompanyCity.Id) ? item.Distance : ((item.city2 == studentCityID && item.city1 == $scope.CompanyCity.Id) ? item.Distance : '');    
    });
    console.log(res[0].Distance); // Distance
};
$scope.findDistance(1); 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
</div>