如何统计对象中typeof值为'object'的属性数量?附遍历代码
Hey there! I see you're working with a deeply nested object/array structure and need to count how many properties have a typeof value of 'object'. Let's fix your current code and also show a more scalable recursive approach—hardcoding nested $.each calls can get messy if your structure has variable depth!
First: Fixing Your Existing Code
Your traversal logic is already laying the groundwork, you just need to add a counter and handle a critical edge case (JavaScript quirk: typeof null returns 'object', which you probably don't want to count). Here's the adjusted version:
// Initialize a counter outside the loops to track the total let objectCount = 0; $.each(Obj, function(k,v){ $.each(v, function(j,l){ $.each(l, function(r,s){ // Check for object type, exclude null, and optionally exclude arrays if(l.hasOwnProperty(r) && typeof s === 'object' && s !== null) { // Add && !Array.isArray(s) here if you don't want to count arrays objectCount++; } }) }) }); console.log(`Total object-type properties: ${objectCount}`);
Better: Use a Recursive Function (For Any Depth)
Hardcoding three layers of $.each only works if your structure is exactly three levels deep. A recursive function will automatically handle any nested depth, making your code way more flexible and maintainable.
Here's a reusable solution:
function countObjectProperties(targetObj) { let totalCount = 0; // Recursive helper to traverse every nested item function traverse(item) { // Skip null (since typeof null incorrectly returns 'object') if (item === null) return; // Only process objects/arrays if (typeof item === 'object') { $.each(item, (key, value) => { // Check if the current value is an object (and not null) if (typeof value === 'object' && value !== null) { // Uncomment below to exclude arrays from the count // if (!Array.isArray(value)) { totalCount++; // } } // Recursively check nested properties/elements traverse(value); }); } } // Start traversing from the top-level object traverse(targetObj); return totalCount; } // Usage example const totalObjects = countObjectProperties(Obj); console.log(`Total object-type properties: ${totalObjects}`);
Key Notes:
- Exclude
null: Always includes !== nullin your check—this avoids counting null values which JavaScript incorrectly labels as objects. - Exclude Arrays: If you don't want arrays to be counted (since
typeof []also returns'object'), uncomment the!Array.isArray(value)condition in the recursive function. - Flexibility: The recursive approach works for any nested structure, whether it's 3 layers deep or 10.
内容的提问来源于stack exchange,提问作者Jose Peres

