I am trying to learn to recursively step through a javascript object. To be more specific, I am doing the recursion problem for functional javascript is good on nodeschool.io. My code is not recursing properly and I can't figure out why.
This is my code so far:
module.exports = function getDependencies (tree) {
var arr = [];
function findKeys(branch) {
var branchHolder = [];
branchHolder = branchHolder.concat(Object.keys(branch));
//console.log(branchHolder);
var filtered = branchHolder.filter(function (value) {
return value !== 'name' && value !== 'version';
})
console.log(filtered);
filtered.forEach(function (twig) {
if (typeof branch[twig] === 'object' && twig === 'dependencies') {
//console.log(twig);
findKeys(branch[twig]);
} else {
//console.log(branch[twig]);
arr.push(twig + '@' + branch[twig].version);
//console.log(arr);
}
/*
//if (branch[twig]) {console.log(branch[twig])}
if (twig !== 'dependencies') {
arr.push(twig + '@' + branch[twig].version)
//console.log(arr)
} else if (typeof branch[twig] === 'object') {
//console.log(branch[twig]);
findKeys(branch[twig]);
}
*/
})
}
findKeys(tree);
return arr.sort();
}
For some reason, my code isn't working. I tested a bare bones version of the code and it seems to work.
function traverse(o) {
if (typeof o === 'object') {
for (var key in o) {
console.log('key: ', key);
traverse(o[key]);
}
} else {
console.log(o);
}
}
a = {foo: 'bar', baz: 'quux', zot: [1, 2, 3, {some: 'hash'}]}
traverse(a)
Can someone tell me what is different between these two blocks of code?
Thank you in advance. :)
Andrew