I want to create a folder tree using a list of objects that contain paths. This solution is working only for a list of strings(paths), but I don't know how to make it work using objects.
var paths = ["About.vue", "Categories/Index.vue", "Categories/Demo.vue", "Categories/Flavors.vue", "Categories/Types/Index.vue", "Categories/Types/Other.vue"],
result = paths.reduce((r, p) => {
var names = p.split("/");
names.reduce((q, name) => {
var temp = q.find(o => o.name === name);
if (!temp) {
q.push((temp = { name, children: [] }));
}
return temp.children;
}, r);
return r;
}, []);
console.log(result)
I want to do the same but instead of using an array of paths using an array of objects that contains paths.
From an array like this:
var paths = [{
path: "/media",
id: 9,
name:"media"
},{
path: "/media/folder1",
id: 1,
name:"folder1"
},{
path: "/media/folder1/child",
id: 3,
name: "child"
},
{
path: "/media/folder2",
id: 2,
name: "folder2"
}];
I want something like this:
[
{
"id": 9,
"name": "media",
"children": [
{
"id": 1,
"name": "folder1",
"children": [
{
"id": 3,
"name": "child",
"children": []
}
]
},
{
"id": 2,
"name": "folder2",
"children": []
}
]
}
]