gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 21:24:31 26 4
gpt4 key购买 nike

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

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

我试图通过对象向下递归,但我不知道如何从每个对象的最内层对象中提取路径

对象也是动态的,由用户创建。

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...
];

最佳答案

这是一个关于如何递归编写此代码的示例:

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);

关于javascript - 从对象属性递归生成文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37825878/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com