Create Dynamic structure for OL LI based on below JSON and also provide JSON data and OL LI structure format also. so please check this.
Json Data format is :
let dataArray = [{
parent1: {
id: 1,
title: 'Parent',
parentId: null,
children: [{
child: {
id: 2,
title: 'Child-1',
parentId: 1,
children: [{
child: {
id: 4,
title: 'Child-1.1',
parentId: 2,
children: [{
child: {
id: 6,
title: 'Child-1.1.1',
parentId: 4,
children: []
}
}]
}
}]
}
}, {
child: {
id: 3,
title: 'Child-2',
parentId: 1,
children: [{
child: {
id: 5,
title: 'Child-2.1',
parentId: 3,
children: []
}
}]
}
}, ]
}
}]
For Sample Example OL LI format :
<ol class="organizational-chart">
<li>
<div>Parent</div>
<ol>
<li>
<div>Child-1</div>
<ol>
<li>
<div>Child-1.1</div>
</li>
</ol>
</li>
<li>
<div>Child-2</div>
<ol>
<li>
<div>Child-2.1</div>
<ol>
<li>
<div>Child-2.1.</div>
<ol>
<li>
<div>Child-2.1.1</div>
</li>
</ol>
</li>
</ol>
</li>
</ol>
</li>
</li>
</ol>
How to create above <ol><li> structure as per below JSON?
var dataArray = [{
parent1: {
id: 1,
title: 'Parent',
parentId: null,
children: [{
child: {
id: 2,
title: 'Child-1',
parentId: 1,
children: [{
child: {
id: 4,
title: 'Child-1.1',
parentId: 2,
children: [{
child: {
id: 6,
title: 'Child-1.1.1',
parentId: 4,
children: []
}
}]
}
}]
}
}, {
child: {
id: 3,
title: 'Child-2',
parentId: 1,
children: [{
child: {
id: 5,
title: 'Child-2.1',
parentId: 3,
children: []
}
}]
}
}, ]
}
}]
function li(){
return document.createElement("li");
}
function ol(){
return document.createElement("ol");
}
function div(){
return document.createElement("div");
}
function addList(rawData, node){
let parent = ol();
const {parent1, parent: parent2, child} = rawData; //since data is not defined, so taking these keys as per data
//taking data
let data;
if(parent1) data = parent1;
else if(parent2) data = parent2;
else data = child;
node.appendChild(parent); //append parent node to the grandParent passed
parent.innerHTML = `<div>${data.title}</div>`; //add title div
data.children?.forEach((ele) => { //loop over children
let child = li();
parent.appendChild(child); //append li tag
addList(ele, child); //run recursion for adding children on this li component
});
}
dataArray.forEach((data) => addList(data, document.getElementById("root")))
<div id="root"></div>
You need to use loops and recurrency for creating the nested list. This is a pseudo-code that you should "translate" into proper javascript.
dataArray.forEach(rootNode => {
const element = createList(rootNode);
document.body.appendChild(element);
});
// create elements
function createList(node) {
const ol = cretateOlElement(node);
node.children.forEach(listItem => {
const li = createListItem(ol, listItem); // recursively check for children and call createList again
ol.appendChild(li);
});
return ol;
}