const products = [{name: 'products1',subcategories: [{name: 'products2',subcategories: []},{name: 'products3',subcategories: [{name: 'products4',subcategories: [],},],},],},{name: 'products5',subcategories: []}];
function buscar(elementos) {
let res = [];
for (let e of elementos) {
res.push(e.name);
if (e.subcategories && e.subcategories.length > 0) {
for (let sub of buscar(e.subcategories)) {
res.push(e.name + "/" + sub);
}
}
}
return res;
}
console.log(buscar(products));
Ahora que tenemos una función que nos retorna TODAS las rutas, buscaremos por ruta, empleando la siguiente logica:
Siendo "B" la ruta a busca, está última debe empezar por "B"
Siempre debemos retornar la ruta más larga (las más profunda)
const products = [{name: 'products1',subcategories: [{name: 'products2',subcategories: [],},{name: 'products3',subcategories: [{name: 'products4',subcategories: [],},],},],},{name: 'products5',subcategories: [],},];
function BuscarPorRuta(ruta, array) {;
let resp = "";
for (let e of buscar(array)) {
if (e.startsWith(ruta)) { //Si la ruta comienza con
if (e.split('/').length >= resp.split('/').length) { //nos quedamos con la ruta mas profunda
resp = e;
}
}
}
return resp;
}
function buscar(elementos) {
let res = [];
for (let e of elementos) {
res.push(e.name);
if (e.subcategories && e.subcategories.length > 0) {
for (let sub of buscar(e.subcategories)) {
res.push(e.name + "/" + sub);
}
}
}
return res;
}
console.log(BuscarPorRuta("products1",products));
console.log(BuscarPorRuta("products5",products));
console.log(BuscarPorRuta("products1/products2",products));