Javascript递归包装 child (俄罗斯套娃)

标签 javascript node.js recursion nested

我在尝试基于类似于下面的 json 文档生成文本文档时遇到困难。

[{
    "title": "item 1",
    "nodes": [{
        "title": "item 1.1"
        "nodes": [{
            "title": "item 1.1.1"
        }, {
            "title": "item 1.1.2"
        }, {
            "title": "item 1.1.3",
            "nodes": [{
                "title": "item 1.1.3.1"
            }, {
                "title": "item 1.1.3.2"
            }, {
                "title": "item 1.1.3.3"
            }]
        }]
    }]
}]

我有一个简单的递归函数,可以正常工作,但是我想生成类似俄罗斯套娃的东西:

<branch title="item 1">
    <branch title="item 1.1">
        <item title="item 1.1.1"></item-end>
        <item title="item 1.1.2"></item-end>
        <branch title="1.1.3">
            <item title="1.1.3.1"></item-end>
            <item title="1.1.3.2"></item-end>
            <item title="1.1.3.3"></item-end>
        <branch-end>
    <branch-end>
<branch-end>

每个 child 都应由 parent 以适当的缩进包装。

关于如何解决这个问题的任何想法?我正在使用 nodejs 顺便说一句!

最佳答案

这样的事情怎么样(使用两个助手来生成 html):

帮助者。

function pad(depth) {return '--'.repeat(depth);}

function makeBranch(title, body, depth) {
  return pad(depth) + '<branch title="'+ title + '">' +
    body + pad(depth) + '<branch-end>';
}

function makeItem(title, depth) {
  return pad(depth) + '<item title="'+ title + '"></item-end>';
}

定义。

function gen(tree, depth) {
  if (!tree.nodes) {
    return makeItem(tree.title, depth);
  } else {
    return makeBranch(tree.title, tree.nodes.reduce(function(str, branch) {
      return str + gen(branch, depth + 1);
    }, ''), depth);
  }
}

用法。

// Pass the root of the tree with depth = 0
gen(tree[0], 0);

//=> Output (formatted here for easier viewing):
"<branch title="item 1">
 --<branch title="item 1.1">
 ----<item title="item 1.1.1"></item-end>
 ----<item title="item 1.1.2"></item-end>
 ----<branch title="item 1.1.3">
 ------<item title="item 1.1.3.1"></item-end>
 ------<item title="item 1.1.3.2"></item-end>
 ------<item title="item 1.1.3.3"></item-end>
 ----<branch-end>
 --<branch-end>
 <branch-end>"

谢谢 zerkms进行更正。

关于Javascript递归包装 child (俄罗斯套娃),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34031285/

相关文章:

javascript - 如何停止空 iframe 在注入(inject)时触发加载事件?

bash - 从 NodeJS 捕获 bash 输出

java - 递归方法,接受输入 s 和 k 并生成长度为 k 的所有字符串

javascript - Lambda 演算——用 Mocking Bird 表达的函数看起来应该是递归的,但事实并非如此

javascript - jQuery .load() 在新选项卡中打开脚本

javascript - 无法分配给的只读属性 '_id'

javascript - 获取所有以类名开头的项目

node.js - 使用 https.request 忽略 node.js 中无效的自签名 ssl 证书?

node.js - 引用错误: t is not defined

javascript - 将数组的每个元素与其后的元素组合