首页 > 解决方案 > 从数组中删除某些项目

问题描述

我正在努力从数组中删除一个项目。该项目需要动态删除。

这是我的代码

大批

{
  "corporateId": "be67e184-a663-439c-b841-c14a734011eb",
  "selectedMAP": [
    {
      "mapId": 79,
      "mapName": "discovery",
      "active": true,
      "options": [
        {
          "optionId": 116,
          "optionName": "comprehensive",
          "memberAmount": 2000,
          "adultDependantAmount": 1500,
          "childDependantAmount": 500,
          "active": true
        }
      ]
    },
    {
      "mapId": 80,
      "mapName": "goodhealth",
      "active": true,
      "options": [
        {
          "optionId": 117,
          "optionName": "keycore",
          "memberAmount": 1000,
          "adultDependantAmount": 600,
          "childDependantAmount": 400,
          "active": true
        },
        {
          "optionId": 119,
          "optionName": "keycore2",
          "memberAmount": 500,
          "adultDependantAmount": 300,
          "childDependantAmount": 200,
          "active": true
        }
      ]
    }
  ]
}

TS

removeOption(index: number, indexOption: number) {
  this.companyMedicalAidProvider[0].selectedMAP[index].options[indexOption].splice(indexOption, 1);
}

HTML

<div id="medicalCard" class="medicalCard" *ngFor="let provider of companyMedicalAidProvider; let i = index;">
...
 <div id="option" class="row option" *ngFor="let providerOptions of companyMedicalAidProvider[0].selectedMAP[i].options; let b = index;">
  <button (click)="removeOption(b,i)">X</button>
 </div>
...
</div>

我在控制台中看到的错误是ERROR TypeError: this.companyMedicalAidProvider[0].selectedMAP[index].options[indexOption].splice is not a function

标签: javascriptangular

解决方案


您必须在数组上调用 splice 而不是在对象本身上调用。将其更改为options.splice应该可以工作:

removeOption(index: number, indexOption: number) {
  this.companyMedicalAidProvider[0].selectedMAP[index].options.splice(
    indexOption,
    1
  );
}

推荐阅读