B
B
buzzi8882014-07-21 13:01:30
JavaScript
buzzi888, 2014-07-21 13:01:30

How to translate a tree structure into a string?

There is a tree (plain JavaScript object):

rootNode
|--NodeA
|----NodeA1
|----....
|--NodeB
|----NodeB1
.....

get a string like
<div rootNode>
    <div NodeA>
          <div NodeA1></div>
    </div>
    .....
</div>

Pseudocode
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);

After the first call, we will have:
<div>RootNode</div>
In the recursion on the second call:
<div>RootNode</div> <div>NodeA</div>
but we need:
<div>RootNode 
     <div>NodeA</div> 
</div>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey, 2014-07-21
@buzzi888

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'>;
}

B
barkalov, 2014-07-21
@barkalov

goessner.net/download/prj/jsonxml

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question