在对象数组中,我想删除所有不具有特定属性的对象。
这是我到目前为止尝试过的:
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;
})
关于javascript - 如何从数组中删除所有不具有特定属性的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59493564/