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

在React.js中如何过滤API返回列表内的空对象与空品牌名数据?

问题原因

你当前的过滤逻辑仅排除了值为单个空格的品牌名称,没有覆盖null、空字符串、undefined、全空格等无效值场景:null != ' ' 的判断结果为true,会导致值为null的品牌项被保留,所以过滤失效。

修复后的代码

{brandsQuery.isLoading ? (
    <span>Loading...</span>
    ) : brandsQuery.isError ? (
    brandsQuery.error.message
    ) : (
    brandsQuery.data.filter(brand => {
      // 先排除品牌名称为null、undefined的情况
      if (brand.brand == null) return false
      // 再排除空字符串、全空格的无效值
      return brand.brand.toString().trim().length > 0
    }).map((filteredBrand) => (
        <div key={filteredBrand.brand} className="form-check">
            <label htmlFor={filteredBrand.brand} className="form-check-label">
                <input
                    className="form-check-label"
                    type="checkbox" 
                    value={filteredBrand.brand}
                    id={filteredBrand.brand} />
                {filteredBrand.brand}
                {console.log('start')}
                {console.log(filteredBrand)}
                {console.log('end')}
            </label>
        </div>
    ))
)}

额外说明

如果需要同时过滤掉整个brand对象为空的情况,可以在过滤逻辑最前面再加一层判断:if (Object.keys(brand).length === 0) return false 即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 06:09:03