You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何实现字符串与数组的匹配筛选?

React 多分类项目筛选实现

问题分析

你当前的代码中,category是字符串类型,而item.category_name是数组类型,直接使用category === item.category_name进行判断永远不会匹配——因为字符串和数组属于不同类型,全等比较必然返回false。

解决方案

要实现「项目的分类数组包含当前选中的分类字符串时,该项目被筛选出来」的需求,只需使用数组的includes()方法,检查数组中是否存在目标字符串:

修改后的代码:

let category = "design" // 可切换为 art、photo 等分类
let filtered = data.filter((item) => item.category_name.includes(category))

额外优化(可选)

如果存在item.category_name为空数组、undefined或null的情况,可以通过可选链操作符避免运行时错误:

let filtered = data.filter((item) => item.category_name?.includes(category))

这样当item.category_name不存在时,表达式会直接返回undefined,filter会自动排除这类不符合条件的项目。

内容的提问来源于stack exchange,提问作者user20826016

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 07:22:05