Get the Number of Keys in an Object using JavaScript

avatar

Borislav Hadzhiev

Mon Oct 25 20211 min read

banner

Photo by Charles Cheng

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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee