Answer the question
In order to leave comments, you need to log in
How to translate a tree structure into a string?
There is a tree (plain JavaScript object):
rootNode
|--NodeA
|----NodeA1
|----....
|--NodeB
|----NodeB1
.....
<div rootNode>
<div NodeA>
<div NodeA1></div>
</div>
.....
</div>
var html = '';
//обход дерева
function traverse(node){
// здесь загвоздка
// нужно вставлять div'ы "втутрь" родительских
// а сейчас получается "плоское" представление, т.е:
// <div>RootNode</div> <div>NodeA</div> <div>NodeA1</div> <div>NodeB</div> .....
html += '<div>'+node.ID+'<div'>'
// рекурсивный вызов для дочерних элементов
traverse(node.childrens);
}
traverse(rootNode);
<div>RootNode</div>
<div>RootNode</div> <div>NodeA</div>
<div>RootNode
<div>NodeA</div>
</div>
Answer the question
In order to leave comments, you need to log in
recursion or breadth-first search (the latter is desirable, but you can get by with regular recursion if your tree is not very nested).
function buildDOM (node) {
var html = '<div node-id='+node.ID+'>';
if (node.childrens.length) {
node.childrens.forEach(function (childNode) {
html += buildDOM(childNode);
}
}
return html + '</div'>;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question