javascript中输出JSON的递归函数

问题描述 投票:1回答:1

使用普通的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();fun(rootdir,object);

希望这很有道理。谢谢!

javascript recursion tree ecmascript-5
1个回答
1
投票

正如注释中指出的,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);
© www.soinside.com 2019 - 2024. All rights reserved.