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


和在JavaScript中一样。

delete myArray[key];

注意,这将元素设置为undefined。

最好使用Array.prototype.splice函数:

const index = myArray.indexOf(key, 0);
if (index > -1) {
   myArray.splice(index, 1);
}

let foo_object; // Itemitem(object here) to remove
this.foo_objects = this.foo_objects.filter(obj => return obj !== foo_object);

这是我的解决方案:

onDelete(id: number) {
    this.service.delete(id).then(() => {
        let index = this.documents.findIndex(d => d.id === id); //find index in your array
        this.documents.splice(index, 1);//remove element from array
    });

    event.stopPropagation();
}

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

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

可以在数组上使用splice方法删除元素。

例如,如果你有一个名为arr的数组,使用以下方法:

arr.splice(2, 1);

因此,这里索引为2的元素将是起点,参数2将决定删除多少个元素。

如果你想删除名为arr的数组的最后一个元素,那么这样做:

arr.splice(arr.length-1, 1);

这将返回删除最后一个元素的arr。

例子:

var arr = ["orange", "mango", "banana", "sugar", "tea"];
arr.splice(arr.length-1, 1)
console.log(arr); // return ["orange", "mango", "banana", "sugar"]

使用TypeScript扩展运算符(…)

// Your key
const key = 'two';

// Your array
const arr = [
    'one',
    'two',
    'three'
];

// Get either the index or -1
const index = arr.indexOf(key); // returns 0


// Despite a real index, or -1, use spread operator and Array.prototype.slice()    
const newArray = (index > -1) ? [
    ...arr.slice(0, index),
    ...arr.slice(index + 1)
] : arr;

还有一个使用Typescript的解决方案:

let updatedArray = [];
for (let el of this.oldArray) {
    if (el !== elementToRemove) {
        updated.push(el);
    }
}
this.oldArray = updated;

Let departments是一个数组。您要从此数组中删除一项。

departments: string[] = [];

 removeDepartment(name: string): void {
    this.departments = this.departments.filter(item => item != name);
  }

下面是一个简单的一行代码,用于按属性从对象数组中删除对象。

delete this.items[this.items.findIndex(item => item.item_id == item_id)];

or

this.items = this.items.filter(item => item.item_id !== item.item_id);

如果你需要从数组中删除一个给定的对象,并且你想确定以下情况,请使用此方法:

列表没有重新初始化 正确更新数组长度

    const objWithIdToRemove;
    const objIndex = this.objectsArray.findIndex(obj => obj.id === objWithIdToRemove);
    if (objIndex > -1) {
      this.objectsArray.splice(objIndex, 1);
    }

只是想为数组添加扩展方法。

interface Array<T> {
      remove(element: T): Array<T>;
    }

    Array.prototype.remove = function (element) {
      const index = this.indexOf(element, 0);
      if (index > -1) {
        return this.splice(index, 1);
      }
      return this;
    };

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);

您可以尝试先获取列表或数组的索引或位置,然后使用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]);
    }
  }

这对我很管用。

你的数组:

DummyArray: any = [
    { "id": 1, "name": 'A' },
    { "id": 2, "name": 'B' },
    { "id": 3, "name": 'C' },
    { "id": 4, "name": 'D' }
]

功能:

remove() {
    this.DummyArray = this.DummyArray.filter(item => item !== item);
}

注意:这个函数删除数组中的所有对象。如果你想从数组中删除一个特定的对象,那么使用这个方法:

remove(id) {
    this.DummyArray = this.DummyArray.filter(item => item.id !== id);
}

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));


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

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' ]


我看到许多抱怨,删除方法不是内置的。考虑使用Set而不是array——它有内置的添加和删除方法。


类似于Abdus Salam Azad的答案,但将数组作为参数 / / https://love2dev.com/blog/javascript-remove-from-array/

function arrayRemove(arr:[], value:any) { 
    
    return arr.filter(function(ele){ 
        return ele != value; 
    });
}

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,表示未找到


_.pull(array,'a'); 

使用lib lodash https://lodash.com/docs/4.17.15#pull complelte代码:

import _ from 'lodash';
const allTagList = ['a','b','b']
_.pull(allTagList, b);
console.log(allTagList) // result: ['a']

PS: Lodash提供了大量的操作符,建议使用它来简化您的代码。https://lodash.com