2017-01-18 36 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); 
}