2017-08-29 28 views
0

这里是我的数据库集合如何找到过滤数组的长度?

{ 
    "_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>  

但我只需要计算那些status ='Y'的用户。这里只USER_NAME = “Athira” 应该算

我怎样才能实现这个

谢谢

回答

4

可以过滤数组是这样的:

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

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

它抛出错误 – Athi

+0

compiler.es5.js:1690未捕获的错误:模板解析错误: 分析器错误:绑定不能在[{{英雄塔25中包含的任务? .users?.filter(u => u.status ==='Y')。length}}] in ng:///AppModule/[email protected]:39(“\t​​{{hero.device_id}} \t​​[ERROR - >] {{英雄。用户.filter(U => u.status === 'Y')长度}?} \t – Athi

+0

​​你试过它在打字稿中的功能?我不确定angular是否可以在html中处理这个问题 –

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'