JavaScript多值过滤数据异常:按type字段过滤无结果求助
多值过滤type字段无结果的解决办法
问题背景
拥有如下数据集:
fee: "20 TEST" id: "1.11.506157" info: "[userlink = newdemo1], send 1 TEST to , [userlink = gs6]" key: "1.11.506157" time: "2022-09-12T07:06:36" type: "transfer" fee: "5 TEST" id: "1.11.396766" info: "[userlink = gs6], upgraded account to lifetime member" key: "1.11.396766" time: "2022-08-29T09:00:18" type: "account_upgrade" fee: "0.00638 TEST" id: "1.11.396764" info: "[userlink = nathan], registered the account , [userlink=gs6]" key: "1.11.396764" time: "2022-08-29T08:59:33" type: "account_create"
需要按type字段进行多值过滤,当前使用的代码如下,但执行后无结果:
const filteredData = allData.filter((e) => e.type === 'account_create' && 'transfer' && 'account_update');
错误原因
你的过滤逻辑完全写错了:
e.type === 'account_create' && 'transfer' && 'account_update'等价于e.type === 'account_create' && true && true,因为非空字符串在布尔判断里永远为真。- 这意味着你只在筛选
type等于account_create的条目,同时你代码里写的account_update在数据集中根本不存在(实际是account_upgrade),而且一个条目不可能同时有多个type值,自然返回空数组。
正确解法
要筛选type属于指定多个值的条目,有两种常用写法:
方法1:用数组includes方法(推荐)
先定义允许的type列表,再判断当前条目是否在列表内:
// 注意:把account_update改成数据集中存在的account_upgrade,按需调整列表 const allowedTypes = ['account_create', 'transfer', 'account_upgrade']; const filteredData = allData.filter(e => allowedTypes.includes(e.type));
方法2:用逻辑或(||)连接判断
直接写出所有符合条件的判断,用||连接:
const filteredData = allData.filter(e => e.type === 'account_create' || e.type === 'transfer' || e.type === 'account_upgrade' );
额外注意
- 务必确认目标
type值和数据集中的一致,你代码里的account_update是笔误,数据集中对应的是account_upgrade,需要修正。 - 多值过滤用
||(满足任意一个条件),而不是&&(同时满足所有条件,单条数据不可能做到)。
内容的提问来源于stack exchange,提问作者sanjK
相关产品推荐
相关产品推荐

