从对象属性递归生成文件路径

时间:2016-06-15 04:00:49

标签: javascript arrays node.js object recursion

我正在使用node.js作为一个副项目我正在创建一个读取.json文件的模块,解析它然后根据object properties&创建目录结构。 object values

对象属性(keys)将是自身/文件和路径的路径。对象值将是该路径的文件列表

我试图向下穿过物体,但我不知道我是如何从每个物体的最内层物体中提取路径的

同样,对象将是dynamic,因为用户将创建。

var path = 'c:/templates/<angular-app>';


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 anyways
    backEnd:[],
    assets:{
      fontAwesome:['font-awesome.css'],
      img:[],
      svg:[]
    }
  }
}

//desired result...
let out = [
  'c:/template name/src/jade/main.jade',
  'c:/template name/src/scripts/index.js',
  'c:/template name/src/scripts/modules/render/index.js',
  'c:/template name/compiled/angular.js',
  'c:/template name/compiled/angular-material.js',
  'c:/template name/compiled/fallback.js',
  'c:/template name/built/frontEnd/',
  'c:/template name/built/backEnd/',
  //...ect...
];

2 个答案:

答案 0 :(得分:1)

以下是一个关于如何递归编写此示例的示例:

&#13;
&#13;
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 anyways
    backEnd: [],
    assets: {
      fontAwesome: ['font-awesome.css'],
      img: [],
      svg: []
    }
  }
}

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

  //item is an object, iterate its properties
  for (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);      
    } else if (Array.isArray(value)) {      
      //if an array
      if (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 results
      recurse(value, newPath, result);
    }
  }

  return result;
}

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

答案 1 :(得分:1)

我对此问题的解决方案如下:

&#13;
&#13;
function getPaths(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 anyways
    backEnd:[],
    assets:{
      fontAwesome:['font-awesome.css'],
      img:[],
      svg:[]
    }
  }
},
   paths = getPaths(template,path);
console.log(paths);
&#13;
&#13;
&#13;

它只是一个名为getPaths的简单函数。实际上它有一个非常基本的递归运行。如果您的对象结构良好(不包括除对象和数组之外的任何属性且没有空值),您甚至可以删除typeof o[k] == "object" && o[k] !== null &&行。很抱歉我的非正统缩进样式,但这是我在使用ES6箭头回调进行三元组,逻辑快捷方式和数组方法时更容易处理代码的方法。