我在TypeScript中创建了一个数组,它有一个属性,我把它用作键。如果我有那把钥匙,我怎么能从里面删除一个项目?


当前回答

Typescript/Javascript中的多个选项可以从数组中删除一个元素。 拼接是最好的选择

它在不创建新对象的情况下删除内联 它正确地更新数组的长度(不会留下空白的null元素)

下面是一个使用Splice函数根据对象数组中的某个字段删除对象的示例

Const persons = [ { 名字:“约翰”, 姓:“米歇尔” }, { 名字:“威廉”, 姓:“斯科特。” }, { 名字:“阿曼达”, 姓:“裁缝” } ] console.log('删除前:'+JSON.stringify(persons)); console.log(“删除威廉:”); persons.splice(人。findIndex(item => item。firstName === 'William'),1); console.log('After Deleting William'+JSON.stringify(persons));

其他回答

您可以尝试先获取列表或数组的索引或位置,然后使用for循环将当前数组分配给临时列表,过滤掉不想要的项并将想要的项存储回原始数组

removeItem(index) {
    var tempList = this.uploadFile;
    this.uploadFile = [];

    for (var j = 0; j < tempList.length; j++) {
      if (j != index)
        this.uploadFile.push(tempList[j]);
    }
  }

在ES6中,你可以使用以下代码:

removeDocument(doc){
   this.documents.forEach( (item, index) => {
     if(item === doc) this.documents.splice(index,1);
   });
}

我们可以使用筛选器和包含来实现逻辑

const checkAlpha2Code = ['BD', 'NZ', 'IN'] let countryAlpha2Code = ['US', 'CA', 'BD', 'NZ', 'AF' , 'AR' , 'BR'] /** * Returns the modified array countryAlpha2Code * after removing elements which matches with the checkAlpha2Code */ countryAlpha2Code = countryAlpha2Code.filter(alpha2code => { return !checkAlpha2Code.includes(alpha2code); }); console.log(countryAlpha2Code) // Output: [ 'US', 'CA', 'AF', 'AR', 'BR' ] // Resetting the values again countryAlpha2Code = ['US', 'CA', 'BD', 'NZ', 'AF' , 'AR' , 'BR'] /** * Returns the modified array countryAlpha2Code * which only matches elements with the checkAlpha2Code */ countryAlpha2Code = countryAlpha2Code.filter(alpha2code => { return checkAlpha2Code.includes(alpha2code); }); console.log(countryAlpha2Code) // Output: [ 'BD', 'NZ' ]

let a: number[] = [];

a.push(1);
a.push(2);
a.push(3);

let index: number = a.findIndex(a => a === 1);

if (index != -1) {
    a.splice(index, 1);
}

console.log(a);
function myFunction(ID){ 
let index = this.myArray.findIndex(d => d.ID === ID); //find index in your array
        console.log('index==',index);
        if (index > -1) {
          console.log('remaving at',index);
          this.myArray.splice(index, 1);//remove element from array
        }
}

注意:你的数组必须有一个名为ID…否则将返回-1,表示未找到