The request for "keys and counts" in a JS object usually means printing all the keys present in the object, and then providing a total count of how many keys there are.
Here's a JavaScript function that does exactly that, returning a single formatted string:
javascript
/**
* Generates a string representation of a JavaScript object,
* listing its keys and the total count of keys.
*
* @param {object} obj The JavaScript object to analyze.
* @returns {string} A formatted string containing the object's keys and their total count.
* Returns an error message if the input is not a valid object.
*/
function printObjectKeysAndCounts(obj) {
// Input validation: Ensure it's a non-null object
if (typeof obj !== 'object' || obj === null) {
return "Error: Input must be a non-null JavaScript object.";
}
// Get all enumerable string properties (keys) of the object
const keys = Object.keys(obj);
// Get the count of the keys
const keyCount = keys.length;
let result = '';
// First line: Total count of keys
result += `Object has ${keyCount} key${keyCount === 1 ? '' : 's'}.\n`;
// Second line: List of keys
if (keyCount > 0) {
result += `Keys: ${keys.join(', ')}`;
} else {
result += `Keys: (None)`;
}
return result;
}
// --- Examples ---
console.log("--- Example 1: Simple Object ---");
const myObject = {
name: "Alice",
age: 30,
city: "New York"
};
console.log(printObjectKeysAndCounts(myObject));
// Expected output:
// Object has 3 keys.
// Keys: name, age, city
console.log("\n--- Example 2: Empty Object ---");
const emptyObject = {};
console.log(printObjectKeysAndCounts(emptyObject));
// Expected output:
// Object has 0 keys.
// Keys: (None)
console.log("\n--- Example 3: Object with numbers as keys (converted to strings) ---");
const numericKeysObject = {
100: "value1",
200: "value2"
};
console.log(printObjectKeysAndCounts(numericKeysObject));
// Expected output:
// Object has 2 keys.
// Keys: 100, 200
console.log("\n--- Example 4: Object with a mix of key types ---");
const mixedKeysObject = {
"firstName": "John",
lastName: "Doe",
'occupation': "Engineer",
_id: "123abc",
$data: [1, 2, 3]
};
console.log(printObjectKeysAndCounts(mixedKeysObject));
// Expected output:
// Object has 5 keys.
// Keys: firstName, lastName, occupation, _id, $data
console.log("\n--- Example 5: Array (arrays are objects too) ---");
const myArray = ["apple", "banana", "cherry"];
console.log(printObjectKeysAndCounts(myArray));
// Expected output:
// Object has 3 keys.
// Keys: 0, 1, 2
console.log("\n--- Example 6: Invalid input (null) ---");
console.log(printObjectKeysAndCounts(null));
// Expected output:
// Error: Input must be a non-null JavaScript object.
console.log("\n--- Example 7: Invalid input (string) ---");
console.log(printObjectKeysAndCounts("hello"));
// Expected output:
// Error: Input must be a non-null JavaScript object.
console.log("\n--- Example 8: Invalid input (number) ---");
console.log(printObjectKeysAndCounts(123));
// Expected output:
// Error: Input must be a non-null JavaScript object.
Explanation:
printObjectKeysAndCounts(obj) function:
Input Validation: It first checks if the provided obj is actually an object and not null. If not, it returns an informative error string.
Object.keys(obj): This is a standard JavaScript method that returns an array of a given object's own enumerable string-keyed property names. This means it gets all the "keys" you typically see in an object literal.
keys.length: Once we have the array of keys, its length property gives us the total count of those keys.
String Construction:
It uses a template literal and string concatenation to build the final output string.