Javascriptrecursion包装儿童(matryoshka娃娃)
我正在尝试生成基于类似于下面的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" }] }] }] }]
我有一个简单的recursion函数,可以正常工作,但是我想生成一个像Matryoshka娃娃的东西:
<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>
每个孩子都应该被父母包装好,并有适当的缩进。
任何想法如何解决这个问题? 我正在使用nodejs btw!
怎么样这样的(使用两个助手的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的更正。
在我的手机上,所以只是一些想法,没有代码。
关键是将树结构压扁成一个数组,其中每个元素都有一个额外的缩进。
你可以很容易地用recursion来压扁树。 那么剩下的就是渲染数组