根据javascript的某些条件查找密钥的计数

时间:2017-01-18 13:07:35

标签: javascript underscore.js

我认为答案Access / process (nested) objects, arrays or JSON与我想要达到的不同。以上链接有关从嵌套数组集中访问对象的问题。

我有一个像下面的对象数组

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

1 个答案:

答案 0 :(得分: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);
}