I have an array of strings
["storage/", "storage/ui/", "storage/inventory/", "storage/model/", "storage/staticmos/", "storage/ui/server.js", "storage/ui/config.js", "storage/ui/elements/", "storage/ui/package.json", "storage/ui/model/", "storage/ui/gulpfile.js", "storage/ui/i18n/", "storage/ui/metadata/", "storage/ui/index.template.html"]
And my purpose is to make a json tree in which every object will contain next properties: name (name of directory/name of file), type(file or directory), path (the actual array entry), id, children (only if the type is directory! empty array if there is nothing in a directory)
So the returned value should look like this:
[
{
id: 1,
name: "Inventory",
type: "directory",
path: "../../elements/storage/Inventory",
children: [
{
id: 2,
name: "inventory.yaml",
type: "file",
path: "../../elements/storage/Inventory/inventory.yaml",
},
],
},
{
id: 3,
name: "UI",
type: "directory",
path: "../../elements/storage/UI",
children: [
{
id: 4,
name: "Model",
type: "directory",
path: "../../elements/storage/UI/Model",
children: [
{
id: 5,
name: "viewmodel",
type: "directory",
path: "../../elements/storage/UI/Model/viewmodel",
children: [],
},
],
},
{
id: 6,
name: "elements",
type: "directory",
path: "../../elements/storage/elements",
children: [],
},
{
id: 7,
name: "i18n",
type: "directory",
path: "../../elements/storage/i18n",
children: [],
},
{
id: 8,
name: "index.template.html",
type: "file",
path: "../../elements/storage/index.template.html",
},
],
},
{
id: 9,
name: "DeviceConnector",
type: "directory",
path: "../../elements/storage/DeviceConnector",
children: [],
},
]
So, I have 2 big problems right now:
- returning after reduce operation object with specific keys
- diferrentiating file from directory.
This is what I got for now:
createObject([...pathes]) {
return pathes.reduce((obj, path) => {
// eslint-disable-next-line no-return-assign
path.split('/').reduce((obj, key) => {"id":'_' + Math.random().toString(36).substr(2, 9),"name":obj[key],"path":path} , obj);
return obj;
}, []);
}