You need to enable JavaScript to run this app. React中如何实现嵌套对象数组按type的name字段过滤
优惠活动
大模型
产品
解决方案
定价
更多

React中如何实现嵌套对象数组按type的name字段过滤

实现方案

原代码问题说明

  • 误用map方法:map用于数组元素转换,返回等长数组,无法实现过滤剔除不符合条件的项,筛选功能需要使用filter方法
  • 未适配数据结构:你的car属性是对象结构,不能直接调用数组的map方法,需要先通过Object.values()提取对象的所有属性值转为数组后再遍历
  • 逻辑缺失:没有判断当前顶层元素是否存在匹配的车型,原代码无论是否匹配都会返回全部顶层元素

首先先修正你给出的示例数据语法错误(JS数组内不能直接写"0": {}键值对,实际接口返回的合法结构应该如下):

const arrayData = [
  {
    "car": {
      "0": {
        "type": {
          name: "sedan", 
          condition: "new"
        }
      },
      "1": {
        "type": {
          name: "minivan", 
          condition: "new"
        }
      }
    }
  },
  {
    "car": {
      "0": {
        "type": {
          name: "sedan", 
          condition: "new"
        }
      }
    }
  },
  {
    "car": {
      "0": {
        "type": {
          name: "minivan", 
          condition: "new"
        }
      }
    }
  }
]

实现代码

场景1:仅过滤顶层元素(car下存在至少一个匹配车型就保留该顶层项,car子项全部保留)

const filterData = (targetType) => {
  // 用filter筛选符合条件的顶层元素
  const filteredData = arrayData.filter(item => {
    // 提取car下所有车辆信息转为数组
    const carList = Object.values(item.car || {})
    // 判断是否存在匹配的车型,不支持可选链可替换为car && car.type && car.type.name
    return carList.some(car => car.type?.name === targetType)
  })
  console.log(filteredData)
  return filteredData
}

// 测试:筛选sedan,会返回arrayData的第0、第1个元素
filterData('sedan') 

场景2:同时过滤顶层元素和car子项(car下仅保留匹配车型,没有匹配项的顶层元素直接剔除)

const filterData = (targetType) => {
  const filteredData = arrayData.reduce((result, item) => {
    // 筛选car下匹配的子项
    const matchedCars = Object.values(item.car || {}).filter(car => car.type?.name === targetType)
    // 存在匹配项就组装新结构推入结果数组
    if (matchedCars.length > 0) {
      result.push({
        ...item,
        // 如果需要car返回数组结构,直接赋值car: matchedCars即可
        car: Object.fromEntries(matchedCars.map((car, idx) => [String(idx), car]))
      })
    }
    return result
  }, [])
  console.log(filteredData)
  return filteredData
}

// 测试:筛选sedan,返回的第0、1个元素car下仅保留sedan子项,第2个元素被直接剔除
filterData('sedan')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 23:45:10