Angular,将三个数组合并到id匹配的数组

时间:2016-08-05 10:05:24

标签: arrays angularjs api merge

我有三个API端点,其中api2和api3都有一个匹配api1 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();

感觉就像一团糟,但这是我成功的唯一途径。还有其他方法可以让这一切变得更容易吗?

1 个答案:

答案 0 :(得分: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;
                    }
                }
            }