How to get the length of an object in JavaScript

OpenJavaScript 0

Last updated: September 27, 2022.

Unlike arrays and strings, JavaScript objects do not have a length property that you can query.

Properties of objects are not stored and accessible numerically, but according to key value only.

So, to get the length requires a little work.

Getting object length with Object.keys()

The simplest way to do this is to call the keys method on the in-built and aptly named Object object, passing in your object. This will return the keys of your object in array format.

This is useful because an array does have a length property. So now all you need to do is query that to get the length of your object:

const myObject = {
  firstName: "Jerry",
  lastName: "Seinfeld",
  occupation: "Comedian",
}

const res = Object.keys(myObject);

console.log(res); // [ "firstName", "lastName", "occupation" ]

console.log(res.length); // 3