Skip to content

Instantly share code, notes, and snippets.

@housker
Last active January 28, 2018 00:27
Show Gist options
  • Save housker/26c0734c9af7815540b6ed8609b5024a to your computer and use it in GitHub Desktop.
Save housker/26c0734c9af7815540b6ed8609b5024a to your computer and use it in GitHub Desktop.
Recursion through nested objects or arrays
myObj = {
name: "Wanda",
children: [
{
name: "Betty",
children: [
{
name: "Jan",
children: []
},
{
name: "Sam",
children: []
}
]
}
]
}
//insert an attribute
// function myFunction(obj) {
// let answer = [];
// answer.push(obj.name);
// return answer;
// }
//insert attribute of child
// function myFunction(obj) {
// let answer = [];
// for (let i = 0; i < obj.children.length; i++) {
// answer.push(obj.children[i].name);
// }
// return answer;
// }
//insert attribute of child of child
// function myFunction(obj) {
// let answer = [];
// for (let i = 0; i < obj.children.length; i++) {
// for (let j = 0; j < obj.children[i].children.length; j++) {
// answer.push(obj.children[i].children[j].name);
// }
// }
// return answer;
// }
//get parents along with children
// function myFunction(obj) {
// let answer = [];
// answer.push(obj.name);
// for (let i = 0; i < obj.children.length; i++) {
// answer.push(obj.children[i].name);
// for (let j = 0; j < obj.children[i].children.length; j++) {
// answer.push(obj.children[i].children[j].name);
// }
// }
// return answer;
// }
//make this recursive
// function myFunction(obj) {
// console.log(obj.name)
// for (let i = 0; i < obj.children.length; i++) {
// myFunction(obj.children[i]);
// }
// }
//keep your "answer" across recursive calls
function myFunction(obj, answer) {
answer = answer || [];
answer.push(obj.name)
for (let i = 0; i < obj.children.length; i++) {
myFunction(obj.children[i], answer);
}
return answer;
}
console.log(myFunction(myObj));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment