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

React中匹配对象name属性后提取对应children数组的问题

你的代码存在3个问题:

  • 属性名拼写错误:代码中写的item.child和实际数据的属性名children不符
  • 匹配逻辑错误:selectedObject是数组类型,不能直接用===和字符串类型的item.name做相等判断
  • 方法选型错误:map会遍历所有元素并返回对应结果,不匹配的项会返回你写的空字符串,不符合仅返回匹配项children的需求

针对testData(对象数组结构)的实现

如果需要返回每个匹配对象的children组成的二维数组:

const result = testData
  // 先筛选出name在选中列表中的对象
  .filter(item => selectedObject.includes(item.name))
  // 提取对应children属性
  .map(item => item.children)

console.log(result)

如果需要把所有匹配的children数组合并为一维数组:

const flatResult = testData
  .filter(item => selectedObject.includes(item.name))
  // flatMap会自动把返回的数组合并为一维
  .flatMap(item => item.children)

console.log(flatResult)

针对testDataTwo(单个对象结构)的实现

const singleResult = selectedObject.includes(testDataTwo.name) ? testDataTwo.children : []
console.log(singleResult)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 05:36:02