I have an array of objects like so,
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
}
]
I want to remove the last object from the array since it has falsy values, I tried to achieve this by writing a simple function like so
function removeFalsy(obj) {
for (let i in obj) {
if (!obj[i]) {
delete obj[i]
}
}
return obj
}
That didn't fix the issue, I also tried to use
arr.map((a) => Object.keys(a).filter((b) => Boolean(b)))
but that just returned the keys in the object, how can I achieve this, please?
Thanks
Assuming that you want to remove all object with falsey values, you can use Array.prototype.filter
on the input array, as well as Array.prototype.every
to check entry values for being falsey
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)
try this
const noFalsies = arr.filter( ( element) => {
const props = Object.values(element)
return ! props.some( (aProp) => !aProp)
}
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.