【问题标题】:Recursive function in javascript that outputs JSONjavascript中输出JSON的递归函数
【发布时间】:2019-11-07 07:06:55
【问题描述】:

在纯 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 对象 = 新对象(); 乐趣(根目录,对象);

希望这是有道理的。 谢谢!

【问题讨论】:

  • 对于初学者,你不能将你的函数命名为function,但除此之外,你也根本没有递归。
  • 你的意思是对象不是 json,对吧?
  • @Andrew - 感谢您指出这一点。我刚刚编辑了名称,现在它反映了我最初的意思。
  • 您可能希望 children 成为一个数组。
  • @ibrahimmahrir 我的意思是对象,是的

标签: javascript recursion tree ecmascript-5


【解决方案1】:

正如 cmets 中所指出的,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);

【讨论】:

  • 这很接近,但应该修改obj(当前未使用)而不是创建新的entryObj。要么,要么不需要接受obj
  • @BrandonHill 好点。我会编辑,谢谢。我完全摆脱了它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-28
  • 2020-01-07
  • 2022-01-07
  • 1970-01-01
  • 2021-09-28
  • 1970-01-01
相关资源
最近更新 更多