javascript - javascript中输出JSON的递归函数
问题描述
在纯 javascript 中,我正在尝试创建一个函数,该函数将返回文件夹、其子文件夹和任何文件的树结构 (json)。我正在尝试使用递归来实现这一点。下面代码的问题是它在第一次递归调用后停止。
我知道在 JS 中你做引用,我需要创建一个新对象,我将之前调用的值传递给它,但我正在努力这样做。
function fun(file, json) {
var tempJson = {
'name' : json.name || '',
'children' : obj.children || new Object()
};
if (file.type == 'file') {
tempJson.type = 'file';
tempJson.children = {}; // this will be empty, since there are no children
}
else {
tempJson.type = 'dir';
var listed = file.listFiles();
if (listed.length > 0) {
for each (var item in listed) {
tempJson.children = fun(item, tempJson);
}
} else {
tempJson.children = {};
}
}
return tempJson;
}
例子
从如下目录结构:
-root
--file1
--dir1
---file1.1
--dir2
我想得到一个像这样的json:
{
name: 'root',
type: 'dir',
children : [
{
name: 'file1',
type: 'file',
children: {}
},
{
name: 'dir1',
type: 'dir',
children:
{
name: 'file1.1',
type: 'file',
children: {},
}
},
name: 'dir2',
type: 'dir',
children: {}
}
第一次调用: var object = new Object(); 乐趣(根目录,对象);
希望这是有道理的。谢谢!
解决方案
正如评论中指出的,children
应该是一个数组:
function fun(entry) {
var entryObj = { // construct the object for this entry
name: entry.name || "",
type: entry.type, // put the type here instead of using an if
children: [] // children must be an array
};
if(entry.type === "dir") { // if this entry is a directory
var childEntries = entry.listFiles(); // get its child entries
for(var childEntry of childEntries) { // and for each one of them
entryObj.children.push(fun(childEntry)); // add the result of the call of 'fun' on them to the children array
}
}
return entryObj;
}
然后像这样调用它:
var tree = fun(rootEntry);
推荐阅读
- javascript - 如果功能组件具有内部可变状态,它可以被认为是纯的吗?
- reactjs - 没有使用 react-router-dom 发送到正确的页面
- swift - 是否可以在模型类中保留数据
- javascript - 在使用 removeChild 时,使用 JavaScript 移动 SVG 对象会阻止 Touchmove 事件
- html - 不同样式和权重的 Web 字体是如何呈现的?
- traefik - 使用带有 Traefik 的请求变量将“WWW”重定向到“Non-WWW”?
- python - 棋盘和棋子检测 OpenCV
- linux-kernel - 谷歌云 - 重启后计算引擎无法与 ssh 连接和串行控制台工作
- javascript - 转场效果不转场就去掉了吗?
- c# - 如何处理可以从一个客户端更改为另一个客户端的对象