Skip to content Skip to sidebar Skip to footer

Recursively Generate Filepaths From Object Properties

I am using node.js and as a side project i am creating a module that reads a .json file ,parse it then create directory structure based on object properties & object values. Ob

Solution 1:

Here's an example on how you can write this recursively:

var path = 'c:/templates';

var template = {
  //outline of 'angular-app'src: {
    jade: ['main.jade'],
    scripts: {
      modules: {
        render: ['index.js'],
        winodws: ['index.js'],
        header: ['header.js', 'controller.js'],
        SCSS: ['index.scss', 'setup.scss'],
      }
    }
  },
  compiled: ['angular.js', 'angular-material.js', 'fallback.js'],
  built: {
    frontEnd: [], //if the array is empty then create the path anywaysbackEnd: [],
    assets: {
      fontAwesome: ['font-awesome.css'],
      img: [],
      svg: []
    }
  }
}

functionrecurse(item, path, result) {
  //create default output if not passed-in
  result = result || [];

  //item is an object, iterate its propertiesfor (let key in item) {
    let value = item[key];
    let newPath = path + "/" + key;

    if (typeof value === "string") {      
      //if the property is a string, just append to the result
      result.push(newPath + "/" + value);      
    } elseif (Array.isArray(value)) {      
      //if an arrayif (value.length === 0) {
        //just the directory name
        result.push(newPath + "/");
      } else {
        //itearate all files
        value.forEach(function(arrayItem) {
          result.push(newPath + "/" + arrayItem);
        });
      }
    } else {
      //this is an object, recursively build resultsrecurse(value, newPath, result);
    }
  }

  return result;
}

var output = recurse(template, path);
console.log(output);

Solution 2:

My solution for this problem would be as follows;

functiongetPaths(o, root = "", result = []) {
  var ok = Object.keys(o);
  return ok.reduce((a,k) => { var p = root + k + "/";
                              typeof o[k] == "object" && o[k] !== null &&
                              Array.isArray(o[k]) ? o[k].length ? o[k].forEach(f => a.push(p+=f))
                                                                : a.push(p)
                                                  : getPaths(o[k],p,a);
                              return a;
                            },result);
}
var path = 'c:/templates/',
template = { 
  //outline of 'angular-app'src:{
    jade:['main.jade'],
    scripts:{
      modules:{
        render:['index.js'],
        winodws:['index.js'],
        header:['header.js' ,'controller.js'],
        SCSS:['index.scss' ,'setup.scss'],
      }
    }
  },
  compiled:['angular.js','angular-material.js' ,'fallback.js'],
  built:{
    frontEnd:[],//if the array is empty then create the path anywaysbackEnd:[],
    assets:{
      fontAwesome:['font-awesome.css'],
      img:[],
      svg:[]
    }
  }
},
   paths = getPaths(template,path);
console.log(paths);

It's just one simple function called getPaths Actually it has a pretty basic recursive run. If your object is well structured (do not include any properties other than objects and arrays and no null values) you may even drop the typeof o[k] == "object" && o[k] !== null && line too. Sorry for my unorthodox indenting style but this is how i find to deal with the code more easy when doing ternaries, logical shortcuts and array methods with ES6 arrow callbacks.

Post a Comment for "Recursively Generate Filepaths From Object Properties"