This short tutorial represents several efficient ways to do it.
The fastest way of counting the keys/properties of an object is to use the following code:
Another efficient solution is to use the following code:
This code works internally iterating over the keys for computing a temporary array. It also returns its length.
The main advantage of this code is that it is clean and readable. But there can be a memory overhead due to the creation of an array.
The next solution is optimizing a for-loop. The slowest part of a for-loop is the .hasOwnProperty() call, due to the function overhead.
So, whenever you want to get the number of entries of a JSON object, you can just skip the .hasOwnProperty() call when you know there is nothing to extend the Object.prototype.
Otherwise, the code might be slightly optimized by transforming key local (var key)and applying the prefix-increment operator (++count)instead of postfix.
Let’s demonstrate it in the example below:
There is another option, which relies on catching the hasOwnProperty method, as follows: