Saturday 15 January 2011

javascript - Convert object to ul li elements -



javascript - Convert object to ul li elements -

i have list of object in array

var mylevel = ['sub', 'topic', 'type'] var mycollection = new array(); mycollection.push({sub: 'book 1', topic: 'topic 1', type: 'mcq'}); mycollection.push({sub: 'book 1', topic: 'topic 1', type: 'mcq'}); mycollection.push({sub: 'book 1', type: 'fib', topic: 'topic 2'}); mycollection.push({sub: 'book 1', topic: 'topic 1', type: 'mtf'}); mycollection.push({sub: 'book 1', topic: 'topic 1', type: 'mcq'}); mycollection.push({sub: 'book 2', type: 'mcq', topic: 'topic 1'}); mycollection.push({sub: 'book 2', topic: 'topic 1', type: 'mcq'}); mycollection.push({sub: 'book 2', topic: 'topic 1', type: 'mcq'});

i want convert these things in proper list ul , li, levels of listing dependent on mylevel variable. book 1 topic 1 mcq mtf topic 2 fib book 2 topic 1 mcq

every section has unique children, cannot have same.

i have tried of creating element loop of mycollection

for(var i=0; i<mycollection.length; i++) { for(var j=0; j<mylevel.length; j++) { createmytree(mycollection[i][mylevel[j]); } } function createmytree(str) { //????????????? }

please help how create element on level needed.

okay, redid , works unless 1 problem: topic 1 get's split 2 topic 1's because topic 2 get's inserted between them.

var mylevel = ['sub', 'topic', 'type']; var mycollection = new array(); mycollection.push({sub: 'book 1', topic: 'topic 1', type: 'mcq'}); mycollection.push({sub: 'book 1', topic: 'topic 1', type: 'mcq'}); mycollection.push({sub: 'book 1', type: 'fib', topic: 'topic 2'}); mycollection.push({sub: 'book 1', topic: 'topic 1', type: 'mtf'}); mycollection.push({sub: 'book 1', topic: 'topic 1', type: 'mcq'}); mycollection.push({sub: 'book 2', type: 'mcq', topic: 'topic 1'}); mycollection.push({sub: 'book 2', topic: 'topic 1', type: 'mcq'}); mycollection.push({sub: 'book 2', topic: 'topic 1', type: 'mcq'}); var dom="<ul>"; var used = new array(); var currentitems = new array(mylevel.length); var lastj = -1; for(var i=0; i<mycollection.length; i++) { var con = false; for(var k=0; k<used.length; k++){ if(compareobjects(used[k], mycollection[i])) con = true; } if(!con){ for(var j=0; j<mylevel.length; j++){ if(currentitems[j] !== mycollection[i][mylevel[j]]){ if(lastj !== -1){ for(var l=0; l<lastj-j; l++){ dom+="</ul></li>"; } } for(var l=j+1; l<currentitems.length; l++) currentitems[l] = ""; currentitems[j] = mycollection[i][mylevel[j]]; dom+="<li>"+currentitems[j]+(j<mylevel.length-1?"<ul>":""); lastj = j; } } used.push(mycollection[i]); } } dom+="</ul>"; $('body').html(dom); function compareobjects(obj1, obj2){ if(obj1.length != obj2.length) homecoming false; for(var el in obj1){ if(obj2[el] === undefined) homecoming false; if(obj1[el] !== obj2[el]) homecoming false; } homecoming true; }

javascript jquery html arrays

No comments:

Post a Comment