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

如何检查Angular响应式表单数组中是否已存在指定对象

解决方案

你的需求核心是将传入对象的键值对映射到FormArray的{id: 键, value: 值}结构中,实现存在则更新,不存在则新增的逻辑。现有代码存在判断条件缺失、FormArray项类型错误(需用FormGroup而非FormControl)、语法错误等问题,以下是修正后的完整实现:

1. 修正表单结构

原表单中address.input是FormArray,每个项需要是包含id和value的FormGroup,才能匹配你期望的结构:

profileForm = this.fb.group({
  firstName: new FormControl(''),
  lastName: new FormControl(''),
  address: this.fb.group({
    input: this.fb.array([]) // 数组内每一项为FormGroup
  }),
});

2. 实现核心方法

编写updateOrAddAddressItems方法替换你的toDo,逻辑如下:

  • 遍历传入对象的键值对
  • 检查FormArray中是否存在id等于当前键的项
  • 存在则更新对应value控件的值;不存在则新建FormGroup并添加到FormArray

代码实现:

// 便捷获取address对应的FormArray
get addressArray(): FormArray {
  return this.profileForm.get('address.input') as FormArray;
}

updateOrAddAddressItems(objParam: {[key: string]: any}) {
  Object.entries(objParam).forEach(([key, value]) => {
    // 查找FormArray中id匹配当前key的项索引
    const existingIndex = this.addressArray.controls.findIndex(
      control => control.get('id')?.value === key
    );

    if (existingIndex !== -1) {
      // 存在则更新value
      this.addressArray.at(existingIndex).get('value')?.setValue(value);
    } else {
      // 不存在则新增FormGroup
      const newItem = this.fb.group({
        id: [key],
        value: [value]
      });
      this.addressArray.push(newItem);
    }
  });
}

3. 调用示例

在组件初始化或需要的时机调用方法:

obj = {
  teste1: 'teste1',
  teste2: 0,
  teste3: 1,
};

ngOnInit() {
  this.updateOrAddAddressItems(this.obj);
}

执行后,profileForm.value的结构会完全符合你的期望:

{
  firstName: "",
  lastName: "",
  address: {
    input: [
      { id: "teste1", value: "teste1" },
      { id: "teste2", value: 0 },
      { id: "teste3", value: 1 }
    ]
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 18:01:23