Count Object Keys in Javascript

March 25, 2020

javascript

Get number of keys in Javascript objects

js
1.Object.keys(yourObject).length;

Usage

js
1.const user = {
2. firstName: "Leonardo",
3. lastName: "Da Vinci",
4. born: "April 15, 1452",
5. death: "May 2, 1519",
6.};
7.
8.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:

js
1.const keyArray = Object.keys(user);
2.
3.console.log(keyArray); // ["firstName", "lastName", "born", "death"]

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

js
1.const numOfKeys = keyArray.length; // or Object.keys(user).length
2.
3.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:

js
1.const user = {
2. firstName: "Leonardo",
3. lastName: "Da Vinci",
4. born: "April 15, 1452",
5. death: "May 2, 1519",
6.};
7.
8.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:

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

The .length property will now return 3 as well:

js
1.const numOfKeys = keyArray.length; // 3