At times, for example, when receiving an object as a function parameter, we wish to know if we have received an empty object or not.
This can especially be the case if some JSON data in a request body is not parsed correctly; our server then ends up with an empty object.
function check4ValidObjectWithKeys(someObj) {
if (Object.entries(someObj).length) {
return "👍🏾"
}
return "👎🏾"
}
Object.entries
...
...along with things like Object.keys
and Object.values
(all would work for the example) creates an array of either...
- The entries - 🔑/value pairs (it's an array of arrays!)
- Just the 🔑s - again, an array
- Just the values - what is it?...an array!
.length
...
...gives us the length (number of items) in an array as a number.
Coercion with if
if (Object.entries(someObj).length) {
translates to:
- Get the entries from the object as an array
- If the length of that array is considered as 'truthy' (non-zero)...
Top comments (0)