Answer the question
In order to leave comments, you need to log in
How to output data object to ul list using recursive function?
How to output data from an array to a multilevel ul list?
There is an array:
const data = [
{"name": "item 1"},
{"name": "item 2"},
{
"name": "item 3",
"children": [
{
"name": "sub item 1",
"children": [{
"name": "sub sub item 1",
}]
},
{"name": "sub item 2"},
{"name": "sub item 3"},
{"name": "sub item 4"}
]
},
{"name": "item 4"}
];
<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3
<ul>
<li>sub item 1
<ul>
<li>sub sub item 1</li>
</ul>
</li>
<li>sub item 2</li>
<li>sub item 3</li>
<li>sub item 4</li>
</ul>
</li>
<li>item 4</li>
</ul>
const data = [ //Массив с данными
{"name": "item 1"},
{"name": "item 2"},
{
"name": "item 3",
"children": [
{
"name": "sub item 1",
"children": [{
"name": "sub sub item 1",
}]
},
{"name": "sub item 2"},
{"name": "sub item 3"},
{"name": "sub item 4"}
]
},
{"name": "item 4"}
];
let ul = document.createElement('ul'); // Создаём ul элемент
let main = document.querySelector('#mainContent').appendChild(ul); // Вставляем его в #mainContent
createTree(data); // Вызываем функцию и передаём в нее массив с данными
function createTree(dat) {
dat.map(item => {
if(item.children) { // Если элемент имеет children
main.innerHTML += '<li>'+item.name+'</li>'; // Вставляем имя элемента
let subItem = document.createElement('ul'); // Создаём новый элемент ul
main = main.appendChild(subItem);
main.innerHTML += createTree(item.children);
}
main.innerHTML += '<li>'+item.name+'</li>';
});
}
Answer the question
In order to leave comments, you need to log in
function createTree(data) {
const ul = document.createElement('ul');
data.forEach(item => {
const li = document.createElement('li');
li.textContent = item.name;
if (item.children) {
li.appendChild(createTree(item.children));
}
ul.appendChild(li);
});
return ul;
}
document.querySelector('#mainContent').appendChild(createTree(data));
const createTree = (data) => `
<ul>${data.map(n => `
<li>
${n.name}
${n.children ? createTree(n.children) : ''}
</li>`).join('')}
</ul>`;
document.querySelector('#mainContent').innerHTML = createTree(data);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question