我有一个像这样的对象数组,
const arr = [
{
'first name': 'john',
'last name': 'doe',
age: '22',
'matriculation number': '12349',
dob: '12/08/1997'
},
{
'first name': 'Jane',
'last name': 'Doe',
age: '21',
'matriculation number': '12345',
dob: '31/08/1999'
},
{
'first name': '',
'last name': undefined,
age: undefined,
'matriculation number': undefined,
dob: undefined
}
]
我想从数组中删除最后一个对象,因为它有错误的值,我试图通过编写一个简单的函数来实现这一点,比如
function removeFalsy(obj) {
for (let i in obj) {
if (!obj[i]) {
delete obj[i]
}
}
return obj
}
这并没有解决问题,我还试着使用
arr.map((a) => Object.keys(a).filter((b) => Boolean(b)))
但那只是返回了对象中的密钥,请问我该如何实现?
感谢
假设要删除所有具有伪值的对象,则可以在输入数组上使用Array.prototype.filter
,也可以使用Array.prototype.every
来检查条目值是否为伪
const arr = [{
'first name': 'john',
'last name': 'doe',
age: '22',
'matriculation number': '12349',
dob: '12/08/1997'
},
{
'first name': 'Jane',
'last name': 'Doe',
age: '21',
'matriculation number': '12345',
dob: '31/08/1999'
},
{
'first name': '',
'last name': undefined,
age: undefined,
'matriculation number': undefined,
dob: undefined
}
];
const result = arr.filter((el) => Object.values(el).every(Boolean));
console.log(result)
尝试这个
const noFalsies = arr.filter( ( element) => {
const props = Object.values(element)
return ! props.some( (aProp) => !aProp)
}
)