Created
April 5, 2017 05:30
-
-
Save shamsher31/6ab0f1fe7fbcf0345a722b34fabba92c to your computer and use it in GitHub Desktop.
Find element in nested array of 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 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