问题
I have my ng-repeat returning arrays like the ones below:
[{"day":"10","title":"day","summary":"summary","description":"ok","_id":"53f25185bffedb83d8348b22"}]
[{"day":"3","title":"day","summary":"summary","description":"ok","_id":"53f25185bffedb83d8348b22"}]
I'd like to create a filter to combine the arrays into one array so that I can use an orderBy | 'day'.
[
{"day":"10","title":"day","summary":"summary","description":"ok","_id":"53f25185bffedb83d8348b22"},
{"day":"3","title":"day","summary":"summary","description":"ok","_id":"53f25185bffedb83d8348b22"
}]
I have a filter used to filter my overall object, but the logic here is much simpler, I'm not sure how to tweak the filter I have to concatenate these objects.
angular.module('hcApp')
.filter('combine', function() {
return function(items) {
var temp = [];
var result = temp.concat.apply(temp,items.map(function(itm){
return temp.concat.apply(temp, Object(itm).map(function(key){
return itm.year[key];
}));
}));
return result;
};
});
回答1:
I think since the data comes as array of arrays 2D and to flatten it out, you could just perform a concat
on your filter.
angular.module('hcApp')
.filter('combine', function() {
return function(items) {
return [].concat.apply([],items)
.sort(function(a,b){ return +a.day < b.day ? -1 : 1; });//and add sort as well probably
};
});
Bin
回答2:
I think you can just use .push()
to join them together. Since each of your returning arrays consist of 1 element, you will need to access the first element of each data, and the push it to another final array.
var some_data_1 = [{"day":"10","title":"day","summary":"summary","description":"ok","_id":"53f25185bffedb83d8348b22"}];
var some_data_2 = [{"day":"3","title":"day","summary":"summary","description":"ok","_id":"53f25185bffedb83d8348b22"}] ;
var temp = [];
//push the first element(the only element) in the returning arrays
temp.push(some_data_1[0], some_data_2[0]);
Here is the working plunkr: http://plnkr.co/edit/t5zRAYmobyYqkEKhrGTd?p=preview
来源:https://stackoverflow.com/questions/25396378/angularjs-filter-to-concat-objects-into-single-array-of-objects