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:
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.
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