代码之家  ›  专栏  ›  技术社区  ›  user6202450

基于特定条件查找键的计数:javascript

  •  0
  • user6202450  · 技术社区  · 8 年前

    我想答案是 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
    

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

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

    1 回复  |  直到 7 年前
        1
  •  0
  •   K D    8 年前

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