0
I created a code to organize a recursive list of categories to print as follows:
- category 1
- -- category 1.1
- category 2
- -- category 2.2
- --- category 2.2.1
json file of data :
const data = {
"categorias": [
{
"id": "6e1ffe88-1ad4-441e-9992-869b81002888",
"categoria_id": null,
"titulo": "Identidade",
},
{
"id": "f30aebbd-b6c4-4aab-bf2d-2a7acad5857d",
"categoria_id": "6e1ffe88-1ad4-441e-9992-869b81002888",
"titulo": "1ª Via",
},
{
"id": "f30d418c-f506-472f-8121-17f15e0f9fed",
"categoria_id": "6e1ffe88-1ad4-441e-9992-869b81002888",
"titulo": "2ª Via",
},
{
"id": "8be426c6-3f54-42aa-a775-ea61241f2553",
"categoria_id": "f30aebbd-b6c4-4aab-bf2d-2a7acad5857d",
"titulo": "Brasileiro Nato",
},
{
"id": "d0c2289d-abbf-44b3-9852-edd170761aa3",
"categoria_id": "8be426c6-3f54-42aa-a775-ea61241f2553",
"titulo": "Até 15 anos",
},
{
"id": "f1b132f4-3565-44b9-ae1e-ca28a139ee92",
"categoria_id": "f30d418c-f506-472f-8121-17f15e0f9fed",
"titulo": "Brasileiro Nato",
},
{
"id": "69e0be42-c767-4427-9b94-994fa01ca042",
"categoria_id": "f1b132f4-3565-44b9-ae1e-ca28a139ee92",
"titulo": "Até 15 anos",
}
]
}
The function below returns the organization I want;
function getNestedChildren(
arr: Categoria[],
parent: string | null,
prof: number,
) {
const out = [];
let cont = prof;
cont += 1;
for (const i in arr) {
if (arr[i].categoria_id === parent) {
const subcategorias = getNestedChildren(arr, arr[i].id, cont);
const categorias = arr;
if (cont > 0) {
let c = 0;
while (c < cont) {
categorias[i].titulo = `---${categorias[i].titulo}`;
c += 1;
}
}
out.push(arr[i]);
if (subcategorias.length) {
subcategorias.forEach(subc => {
out.push(subc);
});
}
}
}
return out;
}
const lista = getNestedChildren(data.categorias, null, -1);
return lista;
}
I would like to have ideas on how to improve the code javascript/typescript using map and filter as the Eslint is accusing error in this code.