Let say i have a object response like this
const response = [
{
"title": "Menu 1",
"subMenu": [
{
"title": "Menu 1.2"
}
]
},
{
"title": "Menu 2",
},
{
"title": "Menu 3",
"subMenu": [
{
"title": "Menu 3.1",
"subMenu": [
{
"title": "Menu 3.2"
}
]
}
]
},
]
I want to get the object have title "Menu 3.1" using recursion so i wrote this function
const findElement = (arr, title) => {
for (let index = 0; index < arr.length; index++) {
const menu = arr[index];
if (menu.title === title) {
return menu;
} else if (menu.subMenu) {
return findElement(menu.subMenu, title);
}
}
};
and call it like this
console.log(findElement(response, "Menu 3.1" ))
but it log 'undefined'? What did i do wrong?
response[0], it goes into menu 1 submenu, and that's it - doesn't even checkresponse[1]