I have a 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 to convert these things in to proper list with ul and li, also the levels of listing is dependent on myLevel variable.
- Book 1
- topic 1
- mcq
- mtf
- topic 2
- fib
- topic 1
- Book 2
- topic 1
- mcq
- topic 1
Every section has a unique children, no duplicate childrens.
I tried this code, but it generates duplicate children
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)
return false;
for(var el in obj1){
if(obj2[el] === undefined)
return false;
if(obj1[el] !== obj2[el])
return false;
}
return true;
}
I get the following result
- Book 1
- topic 1
- mcq
- topic 2
- fib
- topic 1
- mtf
- topic 1
- Book 2
- topic 1
- mcq
- topic 1
Here book 1 has got two topic 1. which is incorrect. i need only 1 topic 1. and that topic 1 should have both mcq and mtf.
Thanks