Last active
August 6, 2016 03:32
-
-
Save eternal44/5dd6f53c8da1c7971c84598003c6e408 to your computer and use it in GitHub Desktop.
Returns a count of all the keys in an array of nested objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function countObjKeys(arr) { | |
var keyCount = 0 | |
function traverseObj(obj) { | |
for (var key in obj){ | |
if(typeof obj[key] === 'object') | |
traverseObj(obj[key]) | |
keyCount++ | |
} | |
} | |
arr.forEach(function(obj) { | |
traverseObj(obj) | |
}) | |
return keyCount | |
} | |
/* | |
############################ | |
# EXAMPLE ARRAY OF OBJECTS # | |
############################ | |
*/ | |
var objArr1 = [ | |
{1: 'one', 2: 'two'}, | |
{3: 'three', 4: | |
{ | |
5: 'five', | |
6: 'six', | |
7: { | |
8: 'eight', | |
9: 'nine', | |
'some': 'thing' | |
} | |
} | |
}, | |
{10: 'ten', 11: 'eleven'}, | |
{12: 'twelve'} | |
] | |
var objArr2 = [ | |
{1: 'one', 2: 'two'}, | |
{3: 'three', 4: | |
{ | |
5: 'five', | |
6: 'six', | |
7: { | |
8: 'eight', | |
9: 'nine', | |
'some': 'thing', | |
'nestedObj': { | |
'another': 'one' | |
} | |
} | |
} | |
}, | |
{10: 'ten', 11: 'eleven'}, | |
{12: 'twelve'} | |
] | |
var objArr3 = [ | |
{1: 'one', 2: 'two'}, | |
{3: 'three'}, | |
{10: 'ten', 11: 'eleven'}, | |
{12: 'twelve'} | |
] | |
console.log(countObjKeys(objArr1)) // 13 | |
console.log(countObjKeys(objArr2)) // 15 | |
console.log(countObjKeys(objArr3)) // 6 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment