I have successfully created a folder tree using a list of string paths. Now, I want to take it a step further and make it work with objects instead.
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)
Instead of an array of paths, I now have an array of objects with paths:
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"
}];
The desired output should look like this:
[
{
"id": 9,
"name": "media",
"children": [
{
"id": 1,
"name": "folder1",
"children": [
{
"id": 3,
"name": "child",
"children": []
}
]
},
{
"id": 2,
"name": "folder2",
"children": []
}
]
}
]