How do I remove an array item in TypeScript?

后端 未结 14 2308
渐次进展
渐次进展 2020-12-07 07:42

I have an array that I\'ve created in TypeScript and it has a property that I use as a key. If I have that key, how can I remove an item from it?

14条回答
  •  天命终不由人
    2020-12-07 08:12

    Use this, if you need to remove a given object from an array and you want to be sure of the following:

    • the list is not reinitialized
    • the array length is properly updated
        const objWithIdToRemove;
        const objIndex = this.objectsArray.findIndex(obj => obj.id === objWithIdToRemove);
        if (objIndex > -1) {
          this.objectsArray.splice(objIndex, 1);
        }
    

提交回复
热议问题