Explain Codes LogoExplain Codes Logo

How to efficiently count the number of keys/properties of an object in JavaScript

javascript
prompt-engineering
performance
best-practices
Alex KataevbyAlex Kataev·Sep 28, 2024
TLDR

To count object keys, use Object.keys(obj).length:

// Want to keep count? Here you go! const keysCount = Object.keys(obj).length;

Example:

// Oh look, a wild object appeared! Let's count its keys! const count = Object.keys({ a: 1, b: 2 }).length; // count is 2

Cross-platform compatibility and performance enhancement

The Object.keys(obj).length works fine across platforms, including Node.js and major browsers such as IE9+. But what if your work involves some antique, legacy systems? A polyfill for Object.keys can be a savior ensuring that older engines can handle the key counting gracefully.

Beware, though! Object.keys() summons a temporary array, which may increase memory use. If your object looks like it swallowed an elephant (i.e., loads of keys), consider the for-in loop:

// Time to loop around town! let count = 0; for (let key in obj) { if (obj.hasOwnProperty(key)) count++; // Found a key? Add to the count }

Take it up a notch with some nifty optimizations:

var hasOwn = Object.prototype.hasOwnProperty; // Caching the check function let count = 0, k; for (k in obj) { if (hasOwn.call(obj, k)) count++; // Found a key? Count it up! }

Using Map for stylish property counting

ES6 upgrades JavaScript with the Map object. It enables storing key-value pairs and offers the .size property. Leverage this to directly get the number of keys sans iteration. Talk about laziness-driven development:

// Let's map the way to our destination const map = new Map([['a', 1], ['b', 2]]); const count = map.size; // Tip: It's not the size that counts!

Libraries' role: Underscore.js and lodash

If you're using Underscore.js or lodash, you can count keys with _.size(obj) or _.keys(obj).length. They offer sweet syntactic sugar and in-house efficiency.

Testing performance in the real-world

Although these methods are theoretically sound, performance may vary based on object size and engine optimization. Use resources such as jsperf.com to conduct appropriate performance tests for your scenario.

Alternative methods for counting

The ES5.1 specification isn't a control freak that mandates native objects to keep track of property counts. Avi Flax proposed an ingenious helper function that mimics Object.keys().length:

// A function a day keeps the problem away! function countProperties(obj) { var count = 0; for (var prop in obj) { if (obj.hasOwnProperty(prop)) ++count; // Up, up and away! } return count; }

Remember, here ++count means incremented before the operation. It's as if the function is saying: "First, I count; later, I relax."

Beware the hidden properties

Not all properties like to show themselves upfront (yeah, they can be shy). Some are non-enumerable, and regular methods like Object.keys() or for-in loops wouldn't count them. Use Object.getOwnPropertyNames(obj) to include all properties.

Potential caveats and solutions

Every method has its limitations. For example, Object.keys(obj).length may not work with deeply nested structures or proxies. Always consider the specifics of your scenario before picking the method.