Angularjs分割阵列的对象结果

问题描述:

我有对象数组是这样的:Angularjs分割阵列的对象结果

{ 
    __v: 0, 
    _id: "5835ced6ffb2476119a597b9", 
    castvote: 1, 
    time: "2016-11-23T17:16:06.676Z", 
    userid: "57e0fa234f243f0710043f8f" 
} 

我怎样才能让一个新的阵列,将通过castvote过滤它们 - 像盛放其中castvote为1的对象的数组,castvote是2吗?

可以在控制器使用$filter为此,

$scope.castvoteOne = $filter('filter')($scope.results, {castvote: 1}); 
$scope.castvoteTwo = $filter('filter')($scope.results, {castvote: 2}); 

DEMO

至于建议here

可以使用Underscore's groupby由你想要的类型一般做到这一点。

_.groupBy($scope.results, "castvote") 

可以使用Array.prototype.reducehash table到组阵列到一个对象与castvote作为具有特定castvote的元素。

现在你可以使用result[castvote]以获取特定castvote

结果见下面的演示:

var array=[{__v:0,_id:"5835ced6ffb2476119a597b9",castvote:1,time:"2016-11-23T17:16:06.676Z",userid:"57e0fa234f243f0710043f8f"},{__v:0,_id:"5835ced6ffb2476119a597b9",castvote:2,time:"2016-11-23T17:16:06.676Z",userid:"57e0fa234f243f0710043f8f"},{__v:0,_id:"5835ced6ffb2476119a597b9",castvote:1,time:"2016-11-23T17:16:06.676Z",userid:"57e0fa234f243f0710043f8f"}] 
 

 
var result = array.reduce(function(hash){ 
 
    return function(p,c) { 
 
    if(!hash[c.castvote]) { 
 
     hash[c.castvote] = []; 
 
     p[c.castvote] = hash[c.castvote]; 
 
    } 
 
    hash[c.castvote].push(c); 
 
    return p; 
 
    }; 
 
}(Object.create(null)),{}); 
 

 
// use result[castvote] to get the result for that castvote 
 
console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}