Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

156
Vistas
Unix-like path converted to json with javascript

I'm migrating from python to javascript. So now, I'm working on a react project where I need to convert some unix-like path to json. Actually, there aren't folders, they're list of categories joined by "/". Here is what I have:

  • Category Model holds the categories and the slug play as categories list joined by "/"
const categorySchema = mongoose.Schema({
    name: { type: String, required: true },
    slug: { type: String, unique: true }, // Repr the route
    image: { type: String },
    topLevel: { type: String },
    description: { type: String },
}, { timestamps: true });

One representation of a category is like this:

{
  name: "embedded",
  slug: "/electronics/embedded",
  image: "/some/image.png",
  topLevel: "electronics",
  description: "This is a brief description."
}

Now what I want is when I have a list of object like this

[
  {
    id: 1,
    name: "embedded",
    slug: "/electronics/embedded",
    image: "/some/image.png",
    topLevel: "electronics",
    description: "This is a brief description."
  },
  {
    id: 2,
    name:"electonics",
    slug:"/electronics",
    topLevel: "electronics",
    image: "/some/image.png",
    description: "..."
  },
  {
    id: 3, 
    name: "house",
    slug: "/house",
    topLevel: "house",
    image: "/some/image.png",
    description: "...",
  }
]

to end up having from the slug which are the unix-like paths as:

[
  {
     id: 2,
     node: "electronics",
     children: [{
       id: 1,
       node: "embedded",
       children: [],
     }],
   },
   {
     id: 3,
     node: "house",
     children: []
   },
]

This is what I'm really struggling trying to have. If someone can help, you are more than welcome.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Based on yesterday's comment on whether I've tried something yet or not, I have basically come up with something but still not perfect because I didn't walk deep the whole tree. Based on the input data and the type of output I want to have, this is my first trial:

function listToTree(list) {
    var node,
        i,
        roots = [];

    for (i = 0; i < list.length; i += 1) {
        node = list[i];
        var slugList = node.slug.split("/").filter((x) => x !== "");
        var children = [];

        if (slugList.length > 1) {
            var parent = slugList.shift();
            var parentNode = {
                node: parent,
                id: node.id,
                children: [],
            };
            roots.push(parentNode);
            for (var j = 0; j < slugList.length; j++) {
                var child = {
                    id: node.id,
                    node: slugList[j],
                    children: [],
                };
                children.push(child);
            }
            roots[i].children = [...children];
        } else {
            roots.push({
                node: node.topLevel,
                id: node.id,
                children: [],
            });
        }
    }
    return roots;
}

The output:

const roots = listToTree(exampleData);
console.log(roots[0]);

{
  node: 'electronics',
  id: 1,
  children: [ { id: 1, node: 'embedded', children: [] } ]
}

So, I still need some help and to be honest this answer here, not yet perfect, was inspired by the answered made by Halcyon in here

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda