To count the number of keys in a JavaScript object, validate that the input is a non-null plain/record object (typeof target === "object" && target !== null && !Array.isArray(target)), use Object.keys(target).length for standard enumerable own string keys inside a try / catch block (or iterate with a for...in / Object.prototype.hasOwnProperty.call / Map when inspecting custom descriptors or avoiding Object.prototype collisions), and keep in mind that while Object.keys(obj).length is the standard fast idiom for own enumerable string keys, micro-benchmarks vary by engine, hidden classes, and object size—so benchmark on your target workload if a hot path demands it.
1. Counting Own Enumerable Keys Safely with Object.keys(obj).length
Validate that inputObj is a non-null non-array object (or accept a Map explicitly via .size), and read Object.keys(inputObj).length inside try / catch:
// Count own enumerable string keys on an object (or size on a Map) safely
function countObjectKeys(inputObj) {
if (inputObj instanceof Map) {
return inputObj.size;
}
if (typeof inputObj !== "object" || inputObj === null || Array.isArray(inputObj)) {
throw new TypeError("Expected inputObj to be a non-null plain/record object or a Map.");
}
try {
return Object.keys(inputObj).length;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(`Failed counting keys on object: ${message}`);
}
}
// Example usage:
// try {
// const userRecord = { id: 101, role: "editor", active: true };
// console.log("Key count:", countObjectKeys(userRecord)); // 3
// } catch (error) {
// console.error(`${error.name}: ${error.message}`);
// }
Object.keys(obj).lengthonly counts own enumerable string keys: It ignores inherited prototype properties and non-enumerable properties.- Avoid counting arrays with
Object.keys(arr).lengthunless you specifically want indices: Usearr.lengthfor arrays.
2. Counting Key Sets Across Multiple Objects with a Map
When recording key counts for multiple named objects or payloads, store results in a Map so dynamic keys never collide with Object.prototype properties:
// Record key counts for multiple named objects into a Map
function countKeysByNameMap(recordsMap) {
if (!(recordsMap instanceof Map)) {
throw new TypeError("Expected recordsMap to be a Map instance.");
}
try {
const countsMap = new Map();
for (const [recordName, recordValue] of recordsMap.entries()) {
if (typeof recordName !== "string" || recordName.trim().length === 0) {
throw new TypeError("Expected every key in recordsMap to be a non-empty string.");
}
countsMap.set(recordName.trim(), countObjectKeys(recordValue));
}
return countsMap;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(`Failed counting keys across Map entries: ${message}`);
}
}
// Example usage:
// try {
// const payloadMap = new Map([
// ["headers", { "content-type": "application/json", accept: "*/*" }],
// ["meta", { page: 1 }]
// ]);
// const resultMap = countKeysByNameMap(payloadMap);
// console.log("Header key count:", resultMap.get("headers")); // 2
// } catch (error) {
// console.error(`${error.name}: ${error.message}`);
// }
- Use
Maprather than a plain{}object for dynamic keys: Avoids collisions withObject.prototypeproperties such asconstructor,toString, orhasOwnProperty. - Use
Map.prototype.sizedirectly forMapcollections:map.sizeis anO(1)property without allocating a key array.
3. Object.keys() vs. Reflect.ownKeys(), Symbols, and Performance Caveats
Keep these object-key-counting details in mind in production code:
- Symbol keys and non-enumerable keys are excluded by
Object.keys(): UseObject.getOwnPropertyNames(obj)for own string keys (including non-enumerable ones) orReflect.ownKeys(obj)when symbol keys must also be counted. - Avoid
for...inwithout an own-property guard: An unguardedfor...inloop walks the prototype chain and can include inherited enumerable properties. - Measure real hot paths rather than assuming micro-optimizations: Modern JS engines optimize
Object.keys(obj).lengthheavily; only optimize further if profiling shows object key enumeration is a bottleneck.
