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

如何渲染列表中包含特定值的对象?JS数组过滤问题解决

问题原因

你的代码存在两个核心错误:

  • 源数据中product是存储所有商品的数组,不存在product.markets这个直接属性,直接访问会得到undefined,对undefined调用filter自然会返回不符合预期的结果
  • 过滤目标错误:你需要过滤的是外层的商品数组,判断每个商品的markets数组是否包含当前市场值,而不是对单个商品的markets数组做等值过滤。
正确实现代码
// 原始数据源
const sourceData = {
  "product": [
    {
      "name": "laptop",
      "markets": ["Portugal", "France"],
      "price": "1000"
    },
    {
      "name": "PS5",
      "markets": ["Portugal", "Spain"],
      "price": "400"
    }
  ]
}

// 替换为你实际的当前市场值
const currentMarket = "Spain"

// 过滤逻辑:遍历商品数组,筛选出markets包含当前市场的商品
const filteredResult = sourceData.product.filter(goods => goods.markets.includes(currentMarket))
运行效果

当currentMarket设为"Spain"时,filteredResult只会返回PS5对应的商品对象;如果设为"Portugal",会返回两个商品对象,完全匹配需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 17:18:24