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


当前回答

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

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

其他回答

使用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;

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

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

这对我很管用。

你的数组:

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

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

departments: string[] = [];

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

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

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