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


当前回答

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

其他回答

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

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

这是我的解决方案:

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();
}
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);
_.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

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

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