如何遍历JSON数据获取文件/目录的完整路径?
生成文件/目录完整路径的递归实现方案
需求
基于给定的JSON数据,从database字段出发,为每个文件和目录生成完整的层级路径,例如logo.png需返回js/assets/icons/logo.png。
现有递归函数的不足
你编写的递归函数仅实现了遍历,但未跟踪当前路径、区分文件/目录类型,也没有收集生成的路径结果:
function iterate(obj){ for(prop in obj){ if(typeof(obj[prop]) == "object"){ iterate(obj[prop]); } } }
修正后的实现方案
以下是可以生成完整路径的递归函数,核心逻辑是跟踪当前路径并区分文件/目录类型,同时收集所有路径结果:
function generateFullPaths(items, currentPath = '', paths = []) { items.forEach(item => { // 拼接当前项的路径片段 const newPath = currentPath ? `${currentPath}/${item.name}` : item.name; if (item.type === 'directory') { // 记录目录自身的完整路径,再递归处理子项 paths.push(newPath); generateFullPaths(item.items, newPath, paths); } else if (item.type === 'file') { // 直接记录文件的完整路径 paths.push(newPath); } }); return paths; } // 使用示例:传入JSON的database字段 const sampleData = { "project-name": "name of the project", "author": "username of the author", "date": "DD-MM-YYYY", "privacy": "public / private", "collaborators": [ "email-address / user-id of Collaborator-1", "email-address / user-id of Collaborator-2" ], "plan": "active-plan-name", "database": [ { "type": "directory", "name": "js", "items": [ { "type": "directory", "name": "assets", "items": [ { "type": "directory", "name": "icons", "items": [ { "type": "file", "name": "logo.png", "content": "path of logo.png" } ] } ] }, { "type": "directory", "name": "lib", "items": [ { "type": "file", "name": "jquery.min.js", "content": "CONTENT OF jquery.min.js" }, { "type": "file", "name": "split.js", "content": "CONTENT OF split.js" } ] }, { "type": "directory", "name": "src", "items": [ { "type": "file", "name": "script.js", "content": "CONTENT OF script.js" } ] } ] }, { "type": "directory", "name": "style", "items": [ { "type": "file", "name": "main.css", "content": "CONTENT OF main.css" } ] }, { "type": "file", "name": "index.html", "content": "CONTENT OF index.html" } ] }; // 调用函数并输出结果 const allPaths = generateFullPaths(sampleData.database); console.log(allPaths);
输出结果
运行上述代码后,会得到所有文件和目录的完整路径数组:
[ "js", "js/assets", "js/assets/icons", "js/assets/icons/logo.png", "js/lib", "js/lib/jquery.min.js", "js/lib/split.js", "js/src", "js/src/script.js", "style", "style/main.css", "index.html" ]
核心逻辑说明
- 路径跟踪:通过
currentPath参数传递当前所在的层级路径,初始为空(根目录)。 - 类型区分:根据
type字段判断是目录还是文件,目录需要递归处理子项,文件直接记录路径。 - 结果收集:通过
paths参数累积所有生成的路径,避免全局变量的使用。
内容的提问来源于stack exchange,提问作者Kshitij Tyagi
相关产品推荐
相关产品推荐

