Split array of file paths into hierarchical object in JavaScript

Using JSZip which when unziping a file gives me a list of folders and files. For example when I run

files.forEach((relativePath, file) => {
  console.log(relativePath);
});

I get:

three-dxf-master/
three-dxf-master/.DS_Store
three-dxf-master/.gitignore
three-dxf-master/LICENSE
three-dxf-master/README.md
three-dxf-master/bower.json
three-dxf-master/bower_components/

Some of these items are directories and some are files.
I can tell which ones are directories by checking file.dir.
I would like to split this into a hierarchical data structure. I want to split it up like so:

{
  "three-dxf-master": [
    ".DS_Store",
    ".gitignore",
    "LICENSE",
    "README.md",
    "bower.json",
    {
      "bower_components": [
        ".DS_Store",
        {
          "dxf-parser": [...]
        }
      ]
    }
  ]
}

This way I can send it over to Vue and format it in a nice file viewer. I looked through the docs and I don’t see an easy way to create a heirarchical data structure for the files. I started looking into this by grabbing the last one in the file path after a split.


Source: stackoverflow-javascript