2017-01-18 34 views
0

我想答案Access/process (nested) objects, arrays or JSON与我想达到的不同。以上链接有关从嵌套数组集合中访问对象的问题。根据特定条件查找钥匙的数量javascript

我有对象像下面

[ 
{ 
    "type": "type 1", 
    "status": "success" 
}, 
{ 
    "type": "type 2", 
    "status": "success" 
}, 
{ 
    "type": "type 1", 
    "status": "error" 
}, 
{ 
    "type": "type 1", 
    "status": "success" 
} 
] 

我打算得到什么数组是这样的

2 type 1 has an event success 
1 type 1 has an event error 
1 type 2 has an event success 

基本上,我想其状态是成功和错误类型的计数。

underscore.js在这里可能很有用,但我无法做到这一点。 帮助,将不胜感激 感谢

+0

[交通/过程(嵌套)对象,数组或JSON(可能的重复http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or -json) – Teemu

+0

被链接的dup候选人接受的答案可以很好地应用于你的任务。如果你需要复印面食的答案,那么它不适合... – Teemu

回答

0

尝试之后,你可以使用_.countBy

var arr = [ 
{ 
    "type": "type 1", 
    "status": "success" 
}, 
{ 
    "type": "type 2", 
    "status": "success" 
}, 
{ 
    "type": "type 1", 
    "status": "error" 
}, 
{ 
    "type": "type 1", 
    "status": "success" 
} 
]; 

var res = _.countBy(arr,function(obj){ 
return obj.type + " has an event " + obj.status 
}); 

for(var item in res) 
{ 
    console.log(res[item] + " " + item); 
}