![](/img/trans.png)
[英]How to remove a simple specific key value pair from all objects and add to one specific object inside an array
[英]Remove a specific object from an object array, filtering by a key and value pair
有什么快速的方法可以從 object 數組中刪除特定的 object,通過鍵值對過濾,而不指定索引號?
例如,如果有一個 object 數組,如下所示:
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))
有沒有什么快速的方法可以從 object 數組中刪除特定的 object,通過鍵和值對過濾,而不指定索引號?
例如,如果有一個 object 數組,如下所示:
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.