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.