Get the Number of Keys in an Object using JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 25, 2021

banner

Photo from Unsplash

Get the Number of Keys in an Object #

To get the number of keys in an object:

  1. Call the Object.keys() method, passing the object as a parameter.
  2. Access the length property on the result.
  3. The Object.keys method returns an array containing the object's keys.
index.js
const obj = { name: 'Tom', age: 30, country: 'Chile', }; const numOfKeys = Object.keys(obj).length; console.log(numOfKeys); // 👉️ 3

We used the Object.keys method to get an array containing the object's keys.

index.js
const obj = { name: 'Tom', age: 30, country: 'Chile', }; console.log(Object.keys(obj)); // 👉️ ['name', 'age', 'country']

The only parameter the method takes is the object for which we want to get the keys.

When called on an empty object, the method returns an empty array.

index.js
console.log(Object.keys({})); // 👉️ []

The last step is to access the length property on the array, to get the number of keys in the object.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.