如何查找已过滤数组的长度?

时间:2017-08-29 10:40:20

标签: angular

这是我的数据库集合

{
    "_id" : ObjectId("59a52c536851fc3289875d14"),
    "device_id" : "ASDFGHJ1234567",
    "users" : [ 
        {
            "user_name" : "Athira",
            "player_level" : "beginner",
            "created_on" : "2017-01-25 09:54:40",
            "updated_on" : "2017-01-25 09:54:40",
            "status" : "Y"
        }, 
        {
            "user_name" : "Sandeep",
            "player_level" : "beginner",
            "created_on" : "2017-01-25 09:54:40",
            "updated_on" : "2017-01-25 09:54:40",
            "status" : "D"
        }
    ],
    "device_created_on" : "2017-01-25 09:54:40",
    "device_status" : "Y"
}

我需要列出设备和用户,如下所示

Device             No: users    Status
 ASDFGHJ1234567       2            Y

这里我使用ngFor来显示这个

<table border="1" cellpadding="5" cellspacing="3">
   <tr>
   <td>Device Id</td>
   <td>Number of Users</td>
   <td>Status</td>
   <td>Action</td>
   </tr>
   <tr *ngFor="let hero of users">
     <td>{{ hero.device_id}}</td>
     <td>{{ hero.users?.length }}</td>
     <td>{{ hero.device_status }}</td>
   </tr>
   </table>      

但我只需要计算那些状态=&#39; Y&#39;的用户。这里只有user_name =&#34; Athira&#34;应该算上

我该如何实现这个

谢谢

2 个答案:

答案 0 :(得分:4)

您可以像这样过滤数组:

getCount(hero: any): number {
 if (!hero || !hero.users) return 0;

 return hero.users.filter(u => u.status === 'Y').length;
}

答案 1 :(得分:0)

您也可以这样做。在你的ts文件中,让arrData作为你的回复

   var data = this.arrData.users;

   var count = 0; var i=0;

   data.forEach(element => {
       if(data[i].status == "Y"){
        count++;
       }
       i++;
   });

   console.log(count); //you will get count value which is users with status 'Y'