如何实现数组过滤:筛选不存在opened键或opened值为false的对象
数据过滤逻辑修正需求
现有一段基于bounce和opened字段过滤数据的代码,其中bounce的过滤逻辑正常:当showbounce不为true时,过滤掉所有bounce值为true的条目。但opened字段仅在消息被打开时才存在,且值固定为true。需要修改代码,实现当showopened不为true时,筛选出**不存在opened字段,或opened值为false**的对象。
现有代码如下:
showBounceOnly(data) { if (this.showbounce !== true) { data = data.filter(item => item.bounce !== true) } if (this.showopened !== true) { data = data.filter(item => item.opened !== true) } this.dataSource = new MatTableDataSource(data); }
示例数据:
[{ "activityDate": "2022-09-18T21:21:06.035Z", "email": ["xxxxxxxe@gmail.com"], "opened": true, "track_request": "track_request::a89a9305-1f53-4175-a6cd-5416b3ebd891", "tracking_nbr": "R_B0PcrD5B" }, { "activityDate": "2022-09-18T21:20:45.674Z", "bounce": true, "email": ["xxxxxxxx@yahoo.com"], "track_request": "track_request::3a82bb14-f59b-4d61-a39f-636b46446261", "tracking_nbr": "WR10YIimW" }, { "activityDate": "2022-09-18T21:20:51.398Z", "email": ["xxxxxxxxxyahoo.com"], "track_request": "track_request::c4bac227-9ea8-45bf-806f-1ac475682764", "tracking_nbr": "XiA3n80oCV" }]
基于上述数据,当showbounce和showopened都不为true时,期望仅返回最后一项。
修正后的代码
只需修改opened字段的过滤条件,将item.opened !== true替换为!item.opened即可:
showBounceOnly(data) { if (this.showbounce !== true) { data = data.filter(item => item.bounce !== true) } if (this.showopened !== true) { // 筛选:不存在opened字段,或opened值为false data = data.filter(item => !item.opened) } this.dataSource = new MatTableDataSource(data); }
逻辑说明:
- 当对象中不存在
opened字段时,item.opened返回undefined,!undefined结果为true,符合筛选条件; - 当
opened字段值为false时,!false结果为true,符合筛选条件; - 只有当
opened字段值为true时,!true结果为false,会被过滤掉,正好满足需求。
内容的提问来源于stack exchange,提问作者MisterniceGuy
相关产品推荐
相关产品推荐

