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
Advertisement
Answer
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)