AngularJS过滤器将对象连接成单个对象数组

时间:2014-08-20 03:41:26

标签: json angularjs angularjs-filter

我的ng-repeat返回数组如下所示:

[{"day":"10","title":"day","summary":"summary","description":"ok","_id":"53f25185bffedb83d8348b22"}]
[{"day":"3","title":"day","summary":"summary","description":"ok","_id":"53f25185bffedb83d8348b22"}]

我想创建一个过滤器,将数组合并为一个数组,以便我可以使用orderBy | '天'

[
{"day":"10","title":"day","summary":"summary","description":"ok","_id":"53f25185bffedb83d8348b22"},
    {"day":"3","title":"day","summary":"summary","description":"ok","_id":"53f25185bffedb83d8348b22"
}]

我有一个过滤器用于过滤我的整体对象,但这里的逻辑要简单得多,我不知道如何调整过滤器我必须连接这些对象。

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;
  };
});

2 个答案:

答案 0 :(得分:2)

我认为,由于数据以2D数组的形式出现并将其展平,因此您只需在滤镜上执行concat即可。

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

答案 1 :(得分:0)

我认为您可以使用.push()将它们连接在一起。由于每个返回的数组都包含1个元素,因此您需要访问每个数据的第一个元素,并将其推送到另一个最终数组。

  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]);

以下是工作人员:http://plnkr.co/edit/t5zRAYmobyYqkEKhrGTd?p=preview