AngularJS filter to concat objects into single array of objects

痞子三分冷 提交于 2020-01-15 09:36:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!