2016-08-05 47 views
0

我有三個API端點,其中api2和api3都獲得了與api1 id匹配的外鍵。Angular,將三個數組合併成一個id匹配的數組

對於現在這是我的代碼,做我想要的(連接ID爲匹配到一個新的數組對象)是什麼,但我想一些幫助,以獲得更乾淨:

$scope.arr = function() { 
     $scope.cars = []; 
     $scope.information = []; 
     $scope.booking = []; 
     $scope.newArr = []; 

     $http({method: 'GET', url: '*api1*'}).success(function(data) { 
      angular.forEach(data, function(value, key) { 
       $scope.cars.push(value); 
      }) 

      $http({method: 'GET', url: '*api2*'}).success(function(data){ 
       angular.forEach(data, function(value, key) { 
        $scope.information.push(value); 
       }) 

       for(var i = 0, car; car = $scope.cars[i]; i++) { 
        for(var j = 0, information; information = $scope.information[j]; j++) { 
          if(car.id === information.carId){ 
           $scope.newArr.push({ 
            "name" : car.name, 
            "city": information.city, 
            "mile": information.mile, 
           }) 
          } 
        } 
       } 

       $http({method: 'GET', url: '*api3*'}).success(function(data){ 
        angular.forEach(data, function(value, key) { 
         $scope.booking.push(value); 
        }) 

        for(var i = 0, car; car = $scope.cars[i]; i++) { 
         for(var j = 0, booking; booking = $scope.booking[j]; j++) { 
           if(car.id === booking.carId){ 
            $scope.newArr.push({ 
             "book" : booking.isBookable, 
            }) 
           } 
         } 
        } 
       }) 
      }) 
     }) 
    } 

$scope.arr(); 

感覺就像一團糟,但我仍然成功的唯一途徑。有沒有其他方法可以讓這一切變得更容易?

+0

查找到第三方庫,我使用[下劃線](http://underscorejs.org/#union) – George

+0

下劃線或lodash都是很好的(_.union (),_.intersection()等) – rrd

+0

我會看看他們。謝謝! – Kazordomo

回答

0

嘗試這種在最後一個循環

for (var i=0;i<$scope.newArr.length;i++) { 
       for (var j=0;j<$scope.booking.length;j++) { 
        if (newArr[i].id === $scope.booking[j].carId) { 
          $scope.newArr[i].id = $scope.booking[j].isBookable; 
        } 
       } 
      } 
相關問題