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 >
<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?
CodePudding user response:
Are you trying to use data with html element and render it or do you wanna add html element into you data
CodePudding user response:
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;
}