Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save shamsher31/6ab0f1fe7fbcf0345a722b34fabba92c to your computer and use it in GitHub Desktop.
Save shamsher31/6ab0f1fe7fbcf0345a722b34fabba92c to your computer and use it in GitHub Desktop.
Find element in nested array of objects
function getMenuById(menu, id) {
if (menu.name == id){
return menu;
}
if (menu.children) {
for (let key in menu.children) {
// console.log(menu.id, ' : ', menu.children[key].name);
if (menu.children[key].name === id) {
return menu.children[key];
}
else if (menu.children[key].children) {
let result = getMenuById(menu.children[key], id);
if (result) {
return result;
}
}
}
}
};
//////
[
{
"name": "Cris",
"age": 30
},
{
"name": "George",
"age": 45,
"children": [
{
"name": "Chris",
"age": 38,
"children": [
{
"name": "Nick",
"age": 35,
"children": [
{
"name": "Maria",
"age": 63
}
]
}
]
}
]
}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment