根据特定条件查找键数 javascript

Find count of a key based on certain conditions javascript

我想答案 Access / process (nested) objects, arrays or JSON 与我想要实现的不同。以上 link 个关于从嵌套数组集中访问对象的问题。

我有一个对象数组,如下所示

[
 {
   "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 在这里可能会有用,但我无法做到这一点。 帮助将不胜感激 谢谢

尝试以下,您可以使用_.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);
}