首页 > 解决方案 > 嵌套树的递归函数不按“顺序”返回

问题描述

我有一个包含嵌套数组的数据结构 - 我想显示数据以使其看起来像一个文件结构 - 所以嵌套数据表示为嵌套文件/文件夹。然而,在控制台记录递归函数返回的内容并不代表数据结构的嵌套性质。

这是我的数据结构:

const data = {
  "root": [
    {
      "type": "folder",
      "name": "one",
      "children": [
        {
          "type": "folder",
          "name": "one",
          "children": []
        },
        {
          "type": "file",
          "name": "two",
          "extension": ".txt",
          "preview": "photos.google.com/abc.jpg"
        },
        {
          "type": "file",
          "name": "four",
          "extension": ".txt",
          "preview": "photos.google.com/abc.jpg"
        }
      ]
    },
    {
      "type": "file",
      "name": "two",
      "extension": ".txt",
      "preview": "photos.google.com/abc.jpg"
    },
    {
      "type": "file",
      "name": "three",
      "extension": ".txt",
      "preview": "photos.google.com/abc.jpg"
    },
    {
      "type": "file",
      "name": "four",
      "extension": ".txt",
      "preview": "photos.google.com/abc.jpg"
    }
  ]
}

我的递归函数:

const recurse = (data, children = false) => {
  data.forEach(object => {
    if (object.type === 'folder') {
      recurse(object.children, true)
    }
    if (children) {
      console.log('   ' + object.type + ' ' + object.name);
    } else {
      console.log(object.type + ' ' + object.name);
    }
  })
}

recurse(data.root)

和控制台日志:

'   folder one'
'   file two'
'   file four'
'folder one'
'file two'
'file three'
'file four'

所以功能是从结构的内部打印出来。如果我想以反映数据结构嵌套性质的方式显示它,我应该使用什么方法?提前致谢

标签: javascriptrecursion

解决方案


@j.xavier.atero 比我快一点。:)

我认为您必须将递归放在函数的末尾。这样你就得到了folder one第一个,然后是它的孩子。

const recurse = (data, children = false) => {
  data.forEach(object => {
    if (children) {
      console.log('   ' + object.type + ' ' + object.name);
    } else {
      console.log(object.type + ' ' + object.name);
    }
    if (object.type === 'folder') {
      recurse(object.children, true)
    }
  })
}

recurse(data.root)

更新评论

我想说为递归函数添加一个额外的参数。

const recurse = (data, level = 0) => {
  data.forEach(object => {
    console.log(Array(level).join('   ') + object.type + ' ' + object.name);

    if (object.type === 'folder') {
      recurse(object.children, level + 1)
    }
  })
}

recurse(data.root)

这会跟踪递归函数的深度。你甚至不需要检查它是否是孩子了。


推荐阅读