Count Object Keys in Javascript

March 25, 2020

Get number of keys in Javascript objects

Object.keys(yourObject).length;

Usage

const user = {
  firstName: "Leonardo",
  lastName: "Da Vinci",
  born: "April 15, 1452",
  death: "May 2, 1519",
};

const numKeys = Object.keys(user).length; // 4

Explanation

Javascript’s Object class has a method, keys(), that returns an array of the object’s own enumerable properties. Since keys() returns an array, we can use the .length property to get the number of array items.

For example, if you console.log out Object.keys(users), you will get an array that contains the object’s keys as strings:

const keyArray = Object.keys(user);

console.log(keyArray); // ["firstName", "lastName", "born", "death"]

We can then use the Array .length property to get the number of items in the keyArray

const numOfKeys = keyArray.length; // or Object.keys(user).length

console.log(numOfKeys); // 4

Object keys and the enumerable Property

One caveat of the Object.keys() method is that it only counts enumerable properties. Most object properties are enumerable, which means this caveat usually only applies to properties that specifically set enumerable to false. We can set a property’s enumerable value by using the Object.defineProperty() method.

For example:

const user = {
  firstName: "Leonardo",
  lastName: "Da Vinci",
  born: "April 15, 1452",
  death: "May 2, 1519",
};

Object.defineProperty(user, "death", { enumerable: false });

The death property is set to enumerable: false, which means it will not show up when using the .keys() method:

const keyArray = Object.keys(user); // ["firstName", "lastName", "born",]

The .length property will now return 3 as well:

const numOfKeys = keyArray.length; // 3