如何将添加/删除项目添加到数组代码



我有一个项目列表,如果选择或取消选择,我想从 myStock中删除或添加项目。我遇到的问题是一旦选择了浏览器粉碎物。我可以做得更好吗?

html:

  <ion-list>
            <div *ngFor="let item of stockList | speciesSearchPipe:listFilter.value">
                <ion-item>
                    <ion-label>
                        {{ item.name_eng }}
                        <img src="./assets/images/species_icons/{{item.image_file}}" width="60" style="float: right;"/>
                    </ion-label>
                    <ion-checkbox class="item-avatar item-checkbox-right" color="dark" checked="false" (click)="selectSpecie(item)"></ion-checkbox>
                </ion-item>
            </div>
  </ion-list>

TS:

let myStock = this.apiService.currentUser.data.coop.jdata;
        if (myStock) {
            for (let x = 0; myStock.stocklist.length > x; x++) {
                myStock.stocklist["fish_species_id"] === item.fish_species_id ? myStock.stocklist.splice(x,1) : myStock.stocklist.push(item);
            };
        } else {
            myStock = {};
            myStock["stocklist"] = [];
            myStock.stocklist.push(item);
        };
        console.log(myStock); // First log is as expected, then the app freezes

尝试用以下方式替换 for -loop:

let index = myStock.stocklist.indexOf(item);
if(index >= 0) {
    myStock.stocklist.splice(index, 1);
} else {
    myStock.stocklist.push(item);
}

完整代码:

let myStock = this.apiService.currentUser.data.coop.jdata;
if (myStock) {
    let index = myStock.stocklist.indexOf(item);
    if (index >= 0) {
        myStock.stocklist.splice(index, 1);
    } else {
        myStock.stocklist.push(item);
    }
} else {
    myStock = {};
    myStock["stocklist"] = [];
    myStock.stocklist.push(item);
};
console.log(myStock);
if (!myStock) {
  myStock = { 
    stockList: [item]
  };
} else {
  const index = myStock.stockList.findIndex(({item.fish_species_id}) => item.fish_species_id === item.fish_species_id);
  if(index !== -1) {
    myStock.stockList[index] = item;
  } else {
    myStock.stockList.push(item);
  }
}
console.log(myStock);

相关内容

  • 没有找到相关文章

最新更新