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

Angular 13中遍历对象数组更新父对象checkedCount的高效实现

Angular 13 高效更新父对象的 checkedCount 属性

我在使用Angular 13开发,手头有一组嵌套结构的对象数组,需要遍历数组,统计每个父对象的children数组中checked属性为true的子对象数量,并将父对象的checkedCount更新为该统计值。

原始数据结构

[
  {
    "name": "Operating System",
    "checkedCount": 0,
    "children": [
      {
        "name": "Linux",
        "value": "Redhat",
        "checked": true
      },
      {
        "name": "Windows",
        "value": "Windows 10"
      }
    ]
  },
  {
    "name": "Software",
    "checkedCount": 0,
    "children": [
      {
        "name": "Photoshop",
        "value": "PS",
        "checked": true
      },
      {
        "name": "Dreamweaver",
        "value": "DW"
      },
      {
        "name": "Fireworks",
        "value": "FW",
        "checked": true
      }
    ]
  }
]

期望结果

[
  {
    "name": "Operating System",
    "checkedCount": 1,
    "children": [
      {
        "name": "Linux",
        "value": "Redhat",
        "checked": true
      },
      {
        "name": "Windows",
        "value": "Windows 10"
      }
    ]
  },
  {
    "name": "Software",
    "checkedCount": 2,
    "children": [
      {
        "name": "Photoshop",
        "value": "PS",
        "checked": true
      },
      {
        "name": "Dreamweaver",
        "value": "DW"
      },
      {
        "name": "Fireworks",
        "value": "FW",
        "checked": true
      }
    ]
  }
]

遇到的问题

我尝试了如下代码,但不仅效率低下,还出现了this.allFilters[i].children[j] may be undefined的错误:

for(let j=0;i<this.allFilters[i].children.length; j++) {
  if (Object.keys(this.allFilters[i].children[j]).length > 0) {
    if (Object.prototype.hasOwnProperty.call(this.allFilters[i].children[j], 'checked')) {
      if(this.allFilters[i].children[j].checked) {
        this.allFilters[i].checkedCount++;
      }
    }
  }
}

高效实现方案

可以利用数组原生方法简化逻辑,同时加入空值判断避免报错,以下两种方案都能高效完成需求:

方案1:使用forEach + filter

this.allFilters.forEach(filter => {
  // 确保children是有效数组,避免undefined报错
  if (Array.isArray(filter.children)) {
    // 过滤出checked为true的子项,直接取长度作为统计值
    filter.checkedCount = filter.children.filter(child => child?.checked === true).length;
  } else {
    // 若children无效,将计数设为0
    filter.checkedCount = 0;
  }
});

方案2:使用forEach + reduce

this.allFilters.forEach(filter => {
  if (Array.isArray(filter.children)) {
    // 累加符合条件的子项数量
    filter.checkedCount = filter.children.reduce((count, child) => {
      return child?.checked === true ? count + 1 : count;
    }, 0);
  } else {
    filter.checkedCount = 0;
  }
});

方案说明

  • 用forEach遍历父数组,比嵌套for循环更简洁易读
  • 加入Array.isArray(filter.children)判断,避免children为undefined或非数组时的报错
  • 使用可选链操作符?.处理子项可能为undefined的情况,避免child.checked抛出异常
  • 原生数组方法filter/reduce性能优于手动嵌套循环,代码逻辑更清晰

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 20:30:50