How could I get the path to a nested value inside this nested array:
const categories = [
{
name: 'category1',
subcategories: [
{
name: 'category2',
subcategories: [],
},
{
name: 'category3',
subcategories: [
{
name: 'category4',
subcategories: [],
},
],
},
],
},
{
name: 'category5',
subcategories: [],
},
];
I need to implement a function that will return something like this:
console.log(getCategoryPath(categories, 'category4')); // should output: '/category1/category3/category4'
So far I've got:
const getCategoryPath() = (categories, categoryName) {
if (category.name === categoryName) {
path = `/${category.name}`;
} else {
category.subcategories.find((firstLevelSubcategory) => {
if (firstLevelSubcategory.name === categoryName) {
path = `/${firstLevelSubcategory.name}`;
} else {
firstLevelSubcategory.subcategories.find(
(secondLevelSubcategory) => {
if (secondLevelSubcategory.name === categoryName) {
path = `/${secondLevelSubcategory.name}`;
}
}
);
}
});
}
}
This prints the matching category name /category4, for example, but I would need to print the whole path to that value /category1/category3/category4.
In this case I'm failing to identify the parent/parents of the matching categoryName. Could I use recursion for this problem and if so, how could I apply it?