Angularjs分割阵列的对象结果
问题描述:
我有对象数组是这样的:Angularjs分割阵列的对象结果
{
__v: 0,
_id: "5835ced6ffb2476119a597b9",
castvote: 1,
time: "2016-11-23T17:16:06.676Z",
userid: "57e0fa234f243f0710043f8f"
}
我怎样才能让一个新的阵列,将通过castvote
过滤它们 - 像盛放其中castvote
为1的对象的数组,castvote
是2吗?
答
可以使用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;}