Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Recursive function to create nested UL

I've been trying to create a nested UL from the following data:

[{"unique_id" : "UFID-06", "level" : "-3"}, 
 {"unique_id" : "UFID-05", "level" : "-2"}, 
 {"unique_id" : "UFID-04", "level" : "-1"}, 
 {"unique_id" : "UFID-03", "level" : "1"}, 
 {"unique_id" : "UFID-02", "level" : "2"},
 {"unique_id" : "UFID-01", "level" : "3"}];

But I'm getting a "too much recursion" message in FireBug.

I'm hoping someone may be able to spot where I'm going wrong in the following:

function process(data) {    
    var childDiv = document.createElement('div');
    for (var i in data) {
        var unique_id = data[i].unique_id;
        var level = data[i].level;

        var ul  = document.createElement('ul');
        var li  = document.createElement('li');
        var txt = document.createTextNode(unique_id + ' : ' + level);

        li.appendChild(txt);
        ul.appendChild(li);
        li.appendChild(txt);

        childDiv.appendChild(ul);
        process(data[i]);
    }
    return childDiv;
}

Here is a fiddle ( https://jsfiddle.net/rt4gL1ff/2/ ). Note that the following line is commented-out, as it will cause the "too much recursion" error when it is executed.

//parentDiv.appendChild(process(obj));

Thanks much!

like image 266
RobertFrenette Avatar asked Mar 15 '26 19:03

RobertFrenette


1 Answers

There is no Stop Condition for process(data[i]);

and also as you can accomplish the task with out using recursive functions

please try this:

var parentDiv = document.getElementById('parentDiv');

var obj = [{"unique_id" : "UFID-06", "level" : "-3"}, 
       {"unique_id" : "UFID-05", "level" : "-2"}, 
       {"unique_id" : "UFID-04", "level" : "-1"}, 
       {"unique_id" : "UFID-03", "level" : "1"}, 
       {"unique_id" : "UFID-02", "level" : "2"},
       {"unique_id" : "UFID-01", "level" : "3"}];

function process(data) {    
    var childDiv = document.createElement('div');
    var prevParent = childDiv; //initially the parent od all ul's should be div
    for (var i in data) {
       var unique_id = data[i].unique_id;
       var level = data[i].level;

       var ul  = document.createElement('ul');
       var li  = document.createElement('li');
       var txt = document.createTextNode(unique_id + ' : ' + level);

       li.appendChild(txt);
       ul.appendChild(li);

       prevParent.appendChild(ul);
       prevParent = ul; //update the parent ul to which the next elements are added
       //process(data,level+1);
   }
   return childDiv;
}

parentDiv.appendChild(process(obj));

checkout the fiddle https://jsfiddle.net/rt4gL1ff/6/

like image 135
Sasidhar Boddeti Avatar answered Mar 18 '26 07:03

Sasidhar Boddeti