lodash.isEmpty([{}]) returns false even though the object contained in the array is empty.
I need something that considers these kind of nested objects empty too and wrote the below recursive function. It looks a bit ugly and doesn't use any JavaScript specific tricks. Any comments welcome.
export function isDeepEmpty(input) {
// catch null or undefined object
if (!input) return true
if (typeof(input) === 'object') {
for (const entry of Object.values(input)) {
if (!isDeepEmpty(entry)) {
return false
}
}
return true
}
// if input is not an object return false
return false
}
EDIT:
Thanks for the comments, this is my improved version.
import isEmpty from 'lodash/fp/isEmpty'
export function isDeepEmpty(input) {
if(isEmpty(input)) {
return true
}
if(typeof input === 'object') {
for(const item of Object.values(input)) {
// if item is not undefined and is a primitive, return false
// otherwise dig deeper
if((item !== undefined && typeof item !== 'object') || !isDeepEmpty(item)) {
return false
}
}
return true
}
return isEmpty(input)
}