DEV Community

Cover image for Empty Object?
Manav Misra
Manav Misra

Posted on

3 3

Empty Object?

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 "👎🏾"
}
Enter fullscreen mode Exit fullscreen mode

Object.entries...

...along with things like Object.keys and Object.values (all would work for the example) creates an array of either...

  1. The entries - 🔑/value pairs (it's an array of arrays!)
  2. Just the 🔑s - again, an array
  3. 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:

  1. Get the entries from the object as an array
  2. If the length of that array is considered as 'truthy' (non-zero)...

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay