Trying to create a function that returns an array of the keys of an object, including of objects nested within. My code looks like this:
function keyCount(obj, arr) {
if (arr == undefined){
arr = []
}
let keys = Object.keys(obj);
let length = keys.length;
for (i = 0; i <= length; i++){
if (Object.keys(obj)[i] !== undefined){
arr.push(Object.keys(obj)[i]);
}
}
for (i = 0; i <= length; i++){
if (typeof(obj[Object.keys(obj)[i]]) === "object" && obj[Object.keys(obj)[i]] !== null && Object.keys(obj)[i] !== undefined){
let nestedobj = obj[Object.keys(obj)[i]];
keyCount(nestedobj,arr)
}
}
return (arr);
}
This returns the first level keys and the keys of one nested object, but exits the function after the first recursive call. Is there a way around this or a better way to format the code? Thanks in advance!
Edited: Data expectations:
let obj1 = {
1:"a",
2:{
3: "b",
4: "c"},
5:{
6:"d",
7: "e",
8: {
9: "f",
10: "g"},
11:{
12:"h",
13: "i"
}
}
};
Should return:
[1,2,5,3,4,6,7,8,9,10,11,12,13]
But only returns:
[1,2,5,3,4]