问题描述
有没有什么快速的方法可以从对象数组中删除特定对象,通过键值对过滤,而不指定索引号?
例如,如果有一个像这样的对象数组:
const arr = [
{ id: 1,name: 'apple' },{ id: 2,name: 'banana' },{ id: 3,name: 'cherry' },...,{ id: 30,name: 'grape' },{ id: 50,name: 'pineapple' }
]
如何在不使用索引号的情况下只删除带有 id: 30
的水果?
我已经想出了一种方式,就像下面的代码,但看起来是一种迂回的方式:
for ( let i = 0; i < arr.length; i++) {
if ( arr[i].id === 30 ) {
arr.splice(i,1);
}
}
解决方法
使用es6标准,可以使用filter方法
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
const arr = [
{ id: 1,name: 'apple' },{ id: 2,name: 'banana' },{ id: 3,name: 'cherry' },{ id: 30,name: 'grape' },{ id: 50,name: 'pineapple' }
];
// !== for strict checking
console.log(arr.filter(e => e.id !== 30))