javascript中输出JSON的递归函数
在纯javascript中,我尝试创建一个函数,该函数将返回文件夹、其子文件夹和任何文件的树结构(json)。我试图通过递归来实现这一点。 下面代码的问题是,它在第一次递归调用后停止 我知道在JS中你需要引用,我需要创建一个新的对象,我将上一次调用的值传递给它,但我很难做到这一点javascript中输出JSON的递归函数,javascript,recursion,tree,ecmascript-5,Javascript,Recursion,Tree,Ecmascript 5,在纯javascript中,我尝试创建一个函数,该函数将返回文件夹、其子文件夹和任何文件的树结构(json)。我试图通过递归来实现这一点。 下面代码的问题是,它在第一次递归调用后停止 我知道在JS中你需要引用,我需要创建一个新的对象,我将上一次调用的值传递给它,但我很难做到这一点 function fun(file, json) { var tempJson = { 'name' : json.name || '', 'children' : obj.children ||
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=新对象();
乐趣(rootdir,object)
希望这是有意义的。
谢谢 正如评论中指出的,
子项
应该是一个数组:
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);
首先,你不能给你的函数命名为
function
,但除此之外,你也根本没有递归。你是说对象不是json,对吗?@Andrew-谢谢你指出这一点。我刚刚编辑了名称,它现在反映了我最初的意思。您可能希望子对象
成为一个数组。@ibrahimmahrir我的意思是对象,是的,这很接近,但应该是修改obj
(当前未使用)而不是创建新的entryObj
。要么这样,要么就没有必要接受obj
@BrandonHill好的观点。我会编辑的,谢谢。我把它全部扔掉了。