我有一个包含这样对象的数组:
{
__v: 0,
_id: "5835ced6ffb2476119a597b9",
castvote: 1,
time: "2016-11-23T17:16:06.676Z",
userid: "57e0fa234f243f0710043f8f"
}
如何创建一个可以通过castvote
过滤它们的新数组 - 就像一个包含castvote
为1的对象的数组,以及castvote
为2的对象?
答案 0 :(得分:3)
您可以使用 $filter ,
在控制器中执行此操作$scope.castvoteOne = $filter('filter')($scope.results, {castvote: 1});
$scope.castvoteTwo = $filter('filter')($scope.results, {castvote: 2});
<强> DEMO 强>
答案 1 :(得分:1)
您可以使用Array.prototype.reduce
和hash 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;}
答案 2 :(得分:0)