I have an requirement to create a tree structure menu from a . separated string array.
My out put should be like following
A
A1
A2
A3
B1
B2
B
B1
B2
B3
B4
C
C1
C2
C4
I am trying to implement that with the following script
<script>
function fnAppend(param) {
var cWin=window.open("","Categories","width=600,height=800,scrollbars=yes");
var array = ['A.A1.A2', 'A.A1.A3', 'A.B1.B2','C.C1.C2','B.B1.B2','B.B1.B3.B4','C4'],
tree = [],
levels = [tree],
last = [];
array.forEach(s => {
var temp = s.split('.');
temp.forEach((name, i) => {
if (last[i] === name) return;
levels[i].push({ name, children: levels[i + 1] = [] });
});
last = temp;
});
function traverse(arr) {
for (const branch of arr) {
console.log('Mother:', branch.name);
var ul=document.createElement('ul');
var li=document.createElement('li');
li.innerHTML="<a href=''>"+branch.name+"</a>";
ul.appendChild(li);
if (Array.isArray(branch.children) && branch.children.length > 0) {
console.log('Children:', branch.children.map(i => i.name).join(', '));
traverse(branch.children);
}
}
var list = document.createElement('div');
list.appendChild(ul);
try {
cWin.document.body.appendChild(list);
} catch (err) {
if (list.outerHTML) {
cWin.document.body.innerHTML = list.outerHTML;
} else {
console.log(err.name);
}
}
}
traverse(tree);
}
</script>
</head>
<body>
<ul id="mylist">
</ul>
<input type="button" value="Append child" onclick="fnAppend('test')" />
</body>
Using above script I am getting the following output
A3
B2
B1
C2
C1
B4
B3
B1
C4
Please help me to format the output. Many thanks in advance.
Regards, Pankaj