Check if a given object is empty without considering any custom props defined by prototype.
Consider this sample object -
|
|
Use Object.entries() or equivalent
Object.entries gives us a short way to access entries in an array form. We could just check whether entries are empty to decide whether the parent object is empty.
|
|
The above logic is unaffected even if the object has defined properties.
|
|
You could also use comparable functions that retrieve keys or values from an object.
|
|
Use a custom function with hasOwnProperty
To check if earth
is empty, you can just do -
|
|
If the object is not empty..
|
|
What not to do?
Note that you cannot check the object directly to check a truthy
condition.
|
|
Recommendation
Use Object.entries()
to check empty conditions unless you really are in love with loops.
Already have an object? Check how you can empty an object in Javascript :)