Check if JavaScript object is empty
28 Jan, 2021
👋 FYI, this note is over 6 months old. Some of the content may be out of date.
if (obj && Object.entries(obj).length === 0 && obj.constructor === Object) {
// do something
}
or use a function:
export const isObjectEmpty = (obj: unknown): boolean => {
if (obj === null || obj === undefined || obj === false) {
return true
}
return Object.entries(obj).length === 0
}
// isObjectEmpty({}) true
// isObjectEmpty({a: 1}) false
You can also invert that function to check if an object has values.
export const isObjectFull = (obj) => !isObjectEmpty(obj)
Not sure about the naming of this one, but you get the idea
← Back home