Count Object Keys in Javascript
March 25, 2020
Get number of keys in Javascript objects
1.Object.keys(yourObject).length;
Usage
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:
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
1.const numOfKeys = keyArray.length; // or Object.keys(user).length2.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:
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:
1.const keyArray = Object.keys(user); // ["firstName", "lastName", "born",]
The .length
property will now return 3
as well:
1.const numOfKeys = keyArray.length; // 3