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

使用.filter()筛选JSON产品数据返回空数组,但原数组非空的问题

问题排查与解决方案

核心问题原因

  • 数组结构处理错误:JSON返回的data是包含products数组的对象,你用Object.keys(data).map(key => data[key])得到的productsArray是二维数组(格式为[ [ {...}, {...} ] ]),而非直接的产品对象数组。此时filter遍历的是外层数组的元素(整个产品数组),该元素没有category属性,因此筛选结果为空。
  • 属性名匹配错误:后续DOM更新时使用了JSON中不存在的product.url、product.image,且product.price本身已包含$符号,重复添加会导致格式错误。

修复步骤

1. 修正产品数组获取方式

直接从data.products提取产品数组,无需多余转换:

// 替换原productsArray的代码
const productsArray = data.products;

2. 验证筛选逻辑

数组结构修正后,原筛选逻辑可正常匹配分类:

const products = productsArray.filter(product => product.category === category);

3. 修复DOM更新的属性名错误

将代码中不存在的属性替换为JSON对应的字段:

products.forEach(function(product, index) {
  const productId = index + 1;
  const productImageId = `product-image-${productId}`;
  const productNameId = `product-name-${productId}`;
  const productPriceId = `product-price-${productId}`;

  // 更新产品图片:使用product.product_url和product.image_url
  document.getElementById(productImageId).innerHTML = `<a href="${product.product_url}"><img src="${product.image_url}" alt="${product.name}"></a>`;

  // 更新产品名称:使用product.product_url
  document.getElementById(productNameId).innerHTML = `<a href="${product.product_url}">${product.name}</a>`;

  // 更新产品价格:原price已带$,无需重复添加
  document.getElementById(productPriceId).innerHTML = product.price;
});

完整修复后的JS代码

$(document).ready(function() {
    // 获取URL中的分类参数
    const urlParams = new URLSearchParams(window.location.search);
    const category = urlParams.get('category');
  
    // 从JSON获取数据
    $.ajax({
      url: 'http://localhost/myprojects/data.json',
      dataType: 'json',
      success: function(data) {
        // 直接获取产品数组
        const productsArray = data.products;
    
        // 按分类筛选产品
        const products = productsArray.filter(product => product.category === category);
        
        // 遍历更新HTML
        products.forEach(function(product, index) {
          const productId = index + 1;
          const productImageId = `product-image-${productId}`;
          const productNameId = `product-name-${productId}`;
          const productPriceId = `product-price-${productId}`;
  
          // 更新产品图片
          document.getElementById(productImageId).innerHTML = `<a href="${product.product_url}"><img src="${product.image_url}" alt="${product.name}"></a>`;
  
          // 更新产品名称
          document.getElementById(productNameId).innerHTML = `<a href="${product.product_url}">${product.name}</a>`;
  
          // 更新产品价格
          document.getElementById(productPriceId).innerHTML = product.price;
        });
      },
      error: function(xhr, status, error) {
        console.log(xhr.responseText);
      }
    });
  });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 22:43:27