如何根据对象的category属性过滤JavaScript数组?
解决数组对象按category属性过滤的问题
你可以直接使用数组的filter()方法,针对每个对象的category属性做判断,就能得到目标过滤结果,代码示例如下:
const base = [ {id: 1, category: 'earth'}, {id: 2, category: 'moon'}, {id: 3, category: 'earth'} ]; const filtered = base.filter(item => item.category === 'earth'); console.log(filtered);
关键说明
filter()方法会遍历数组每一项,回调函数返回true时,当前项会被保留到新数组中,不会修改原数组,需要将返回值赋值给变量才能拿到结果。- 回调里通过
item.category === 'earth'精准匹配属性值,确保只有符合条件的对象被筛选。
排查之前失败的可能原因
- 属性名/匹配值拼写错误:比如把
category写错,或者'earth'大小写不一致(比如写成'Earth') - 逻辑判断错误:误用赋值符号
=代替全等判断=== - 未接收返回值:忘记将
filter()的结果赋值给变量,直接操作原数组
内容的提问来源于stack exchange,提问作者crinnsh
相关产品推荐
相关产品推荐

