Merge an array of arrays in AngularJS

2019-07-24 21:53发布

问题:

I have the following controller which was a result of another OP on Stack Overflow.

var getData = function() {
        var swindon = $http.get('(url)/swi/10?expand=true'),
            paddington = $http.get('(url)/pad/10?expand=true'),
            reading = $http.get('(url)/rdg/10?expand=true');
        $q.all([swindon,paddington,reading]).then(function(arrayOfResults) {
            $scope.listOfServices = arrayOfResults;
            console.log($scope.listOfServices);
        });
    };

  getData();

Which results in something like this

What I would like to do NOW is CONCAT these three arrays into ONE array. The arrays are absolutly identical in structure with the records being stored in the trainServices array

I have tried something along the lines of

$scope.listOfServices = $scope.listOfServices.data.concat(data);

which comes back as undefined

I can use the arrays in a nested NG-REPEAT, but I need to filter out duplicates from the three arrays, so I need them as one. The data is from a live feed so I cannot do the query before the data gets to the app.

This is how I call the arrays at the moment

<tbody ng-repeat="item in listOfServices">
      <tr ng-repeat="service in item.data.trainServices | customDelayFilter">

I have also included an ONLINE JSON representation of JSON.stringify($scope.listOfServices)

Not sure why the top level says JSON.. thats not actually a string in the output

回答1:

you can try:

$scope.listOfServices = [].concat(...arrayOfResults.map(item => item.data.trainServices));

it should give you concated array of trainServices' objects

arrayOfResults.map(item => item.data.trainServices)

this code in our case returns an array of three trainServices arrays, using Array.prototype.map function

...arrayOfResults.map(item => item.data.trainServices)

this code uses spread operator, which enables us to pass our array of arrays to Array.prototype.concat function, which merges those arrays of objects