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

TypeScript不使用forEach遍历对象数组:代码返回空数组的错误排查

问题:获取数组中isSelected为true的item值失败原因分析

原始数据结构

[
    {
        "matListParent": "CH",
        "dParent": "CUST1",
        "isAllSelected": true,
        "childItems": [
            {
                "item": "Display1",
                "isSelected": true
            },
            {
                "item": "Display2",
                "isSelected": false
            }
        ]
    },
    {
        "matListParent": "CH2",
        "dimParent": "CUST2",
        "isAllSelected": true,
        "childItems": [
            {
                "item": "Display5",
                "isSelected": true
            },
            {
                "item": "Display6",
                "isSelected": false
            }
        ]
    }
]

你编写的代码

data.filter(
        (matModel: any) => matModel.matListParent === "CH").map(
          (model: any) => model.childItems).map((item: any) => item).filter((list: any) => list.isSelected);

错误原因分析

  • 二维数组未展开,过滤对象错误:代码执行流程存在逻辑问题:
    1. filter后得到包含1个父对象的数组;
    2. map(model => model.childItems)将父对象转为对应的childItems数组,此时结果是二维数组:[[{item: "Display1", ...}, {item: "Display2", ...}]];
    3. 中间的map((item: any) => item)是冗余操作,对数组无任何修改;
    4. 最后filter((list: any) => list.isSelected)是在过滤二维数组的外层数组元素(也就是子数组),但子数组本身没有isSelected属性,因此过滤后返回空数组。
  • 缺少提取item值的步骤:即使过滤逻辑正确,代码也没有提取最终需要的item字段值。

正确实现方式

方式一:使用flatMap展开数组

const selectedItems = data
  .filter(matModel => matModel.matListParent === "CH")
  .flatMap(model => model.childItems) // 将二维数组展开为一维子项数组
  .filter(child => child.isSelected) // 筛选isSelected为true的子项
  .map(child => child.item); // 提取item字段值

方式二:使用reduce统一处理

const selectedItems = data.reduce((result, matModel) => {
  if (matModel.matListParent === "CH") {
    // 筛选当前父项中选中的子项并提取item值
    const currentSelected = matModel.childItems
      .filter(child => child.isSelected)
      .map(child => child.item);
    result.push(...currentSelected);
  }
  return result;
}, [] as string[]);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 23:35:41