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

如何基于FormArray内FormControl取值分组并对组内字段求和

遍历分组Map的实现方式

你得到的是标准ES6 Map结构,可直接使用原生方法遍历键值对,两种常用写法如下:

写法1:使用forEach遍历

// grouped就是你分组后得到的Map实例
grouped.forEach((formControlList, treeTypeCode) => {
  // treeTypeCode 是分组的键,也就是treeType的code值
  // formControlList 是当前分组下的所有表单控件集合数组
  console.log('当前分组code:', treeTypeCode, '分组内的条目数:', formControlList.length);
})

写法2:使用for...of遍历

for (const [treeTypeCode, formControlList] of grouped.entries()) {
  // 同样可以拿到分组键和对应的表单集合,按业务需求处理即可
}

分组内指定FormControl求和实现

假设你需要对quantityOfTrees控件的取值求和,直接在遍历分组时累加对应控件的value即可,示例如下:

// 定义存储各分组求和结果的对象
const sumResult = {};

grouped.forEach((formControlList, treeTypeCode) => {
  // 初始化当前分组的求和值
  let total = 0;
  formControlList.forEach(item => {
    // 取指定FormControl的value累加,增加类型转换和非空判断避免出现NaN
    const value = Number(item.quantityOfTrees.value) || 0;
    total += value;
  })
  sumResult[treeTypeCode] = total;
})

// 最终sumResult的结构为 {2: 求和结果, 4: 求和结果},可直接用于后续业务逻辑

如果需要动态指定求和的控件名,可以把逻辑封装成通用函数:

function calcGroupSum(groupedMap: Map<any, any[]>, controlName: string) {
  const result = {};
  groupedMap.forEach((list, key) => {
    result[key] = list.reduce((sum, item) => sum + (Number(item[controlName]?.value) || 0), 0);
  })
  return result;
}

// 调用示例,求quantityOfTrees的分组和
const quantitySum = calcGroupSum(grouped, 'quantityOfTrees');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 07:06:10