Search code examples
javascriptarraysjsonobjectreduce

Creating a JSON tree with specific keys and values by array of strings


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:

  1. returning after reduce operation object with specific keys
  2. differentiating 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;
    }, []);
  }

Solution

  • You could utilize the last slash and use it for changing the type.

    const
        data = ["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"],
        result = data.reduce((r, path) => {
            path.split('\/').reduce((level, name) => {
                if (name === '') {
                    level.type = 'directory';
                    return;
                }
                let directory = (level.children = level.children || []).find(q => q.name === name);
                if (!directory) level.children.push(directory = { id: '_' + Math.random().toString(36).substr(2, 9), name, type: 'file', path });
                return directory;
            }, r);
            return r;
        }, {}).children;
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }