我有一張CItyDistance表:CIty1Id | City2Id |距離(KM), 現在在我的項目中,我收到2個城市的ID,我想檢查是否存在這兩個城市的計算距離。Angular.js在給定屬性中搜索數組中的匹配對象
所以無論誰是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);
檢查我的答案,將工作按照您的期望。 –