I've an array of nested objects. They represent a folder-like path or a menu with sub-navigation.
The structure is like it follows:
const MENU:Menu[] = [
{
value: 'Home',
nested: [
{ value: 'home-1', url: 'home-1' },
{ value: 'home-2', url: 'home-2' },
],
},
{
value: 'about',
nested: [
{
value: 'about-1',
url: 'about-1',
},
{
value: 'about-2',
url: 'about-2',
},
],
},
];
I want that for a given url to return the path using the value property.
For example, for home-1 => ['Home','home-1']
for about-2 => ['about','about-2']
The interface for this Menu is
interface Menu {
value: string;
nested?: Menu[];
url?: string;
}
This is what I tried
function getPath(url, menu = MENU, navTreePath = []) {
for (let i = 0; i < menu.length; i++) {
const currentMenu = menu[i];
if (currentMenu.url === url) {
navTreePath.push(currentMenu.value);
return navTreePath;
} else if (currentMenu.nested) {
navTreePath.push(currentMenu.value);
return getNavTreePathFromUrl(url, currentMenu.nested, []);
} else {
}
}
}
And the call
const path = getPath('about-2');