簡體   English   中英

如何從數組中刪除所有沒有特定屬性的對象?

[英]How to remove from an array all objects that don't have a certain property?

在對象數組中,我想刪除所有沒有特定屬性的對象。

這是我到目前為止嘗試過的:

myArray.splice(myArray.findIndex(item => item.myProperty === null), 1)

它似乎不起作用。 我應該怎么做?

每當您有一個數組並且想要刪除某些項目時,請將其視為“過濾”問題

const hasProp = prop => item => {
   // if the prop is in the item, returns true
   return prop in item;
}

// filter takes a predicate function (1 param, returns true/false)
// filter is 'immutable' i.e. returns a new array
const filteredArray = myArray.filter(hasProp('myProperty'))

以上創建了一個可重用的過濾函數(高階函數)。 它也可以用一種不太可重用(功能較少的編程)的方式來編寫:

const filteredArray = myArray.filter( item => {
    return 'myProperty' in item;
})

您可以使用filter來刪除項目。 最終返回的數組將包含所需的值。

 const fruits = [ { color: 'yellow', name: 'banana' }, { color: 'yellow', name: 'mango' }, { color: 'green', name: 'guava' } ]; const colorToRemove = 'yellow'; const filteredFruit = fruits.filter((item) => item.color !== colorToRemove); console.log(filteredFruit);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM