Friday, 17 March 2017

NodeJS: How to dynamically generate an object structure?

Hello world's best community!

I'm as new to stackoverflow.com as I am to JavaScript, so apologies in advance if this question gonna sound somewhat amateur.

I'm currently working on a small application(learning exercise) and require to generate an object based on a folder structure. Here is an example of the folder structure:

RootFolder/FolderA/FolderB/FileA

RootFolder/FolderA/FolderB/FileB

RootFolder/FolderA/FolderB/FolderC/FileA

RootFolder/FolderA/FolderB/FolderC/FileB

The desired resulting object should have the following structure:

{
    RootFolder: {
        FolderA: {
            FolderB: {
                FileA: {},
                FileB: {},
                FolderC: {
                    FileA: {},
                    FileB: {}
                }
            }
        }
    }
};

So far I came up with the following code and it seems to be doing the job, but I'm concerned with 'eval' use and generally believe there is a more elegant way of doing it.

module.exports = {
  structure: function(structureArray) {
    var generatedObject = {};
    for (var i = 0; i < structureArray.length; i++) {
      var objectElements = '';
      var path = (structureArray[i].split('/')).filter(Boolean);
      for (var l = 0; l < path.length; l++) {
        if (objectElements.indexOf(path[l]) == -1 || path[l].length == 1) {
          objectElements += '["' + path[l] + '"]';
        }
        if (!(eval('generatedObject' + objectElements))) {
          eval('generatedObject' + objectElements + '= {}')
        }
      }
    }
    return generatedObject;
  }
};

'structureArray' contains full path strings as in the folder structure example above(e.g. 'RootFolder/FolderA/FolderB/FileA')

Any advice on the code improvements is much appreciated.

Regards,



via ShamrockDOB

No comments:

Post a Comment