const data = [
{
id: 1122031,
title: "Banner",
children: [
{
id: 1122032,
title: "prod 1"
},
{
id: 1122033,
title: "prod 2"
},
{
id: 1122034,
title: "prod 3"
},
{
id: 1366085,
title: "prod 6",
children: [
{
id: 1362085,
title: "prod 16"
}
]
}
]
}
];
function createTree(data, defaultId) {
const ul = document.createElement("ul");
data.map((item, index) => {
const li = document.createElement("li");
li.textContent = item.id;
if (item.children) {
li.appendChild(createTree(item.children, index));
}
ul.appendChild(li);
});
return ul;
}
<ul>
<li>
children
<ul>
<li>
0_children
<ul>
<li>0_children_0</li>
<li>0_children_1</li>
<li>0_children_2</li>
<li>
0_children_3
<ul>
<li>
0_children_3_children_0
</li>
<li>
0_children_3_children_1
</li>
</ul>
</li>
</ul>
</li>
<li>
1_children
</li>
</ul>
</li>
</ul>
const createTreeElement = (data, index = []) =>
Array.isArray(data) && data.length
? data.reduce((ul, n, i) => (
index.push(i),
ul.append(document.createElement('li')),
ul.lastChild.append(index.join('_'), createTreeElement(n.children, index)),
index.pop(),
ul
), document.createElement('ul'))
: '';
document.body.append(createTreeElement(data));
const createTreeHTML = (data, index = '') =>
data instanceof Array && data.length
? `<ul>${data.map((n, i) => `
<li>
${(i = index + (index && '_') + i)}
${createTreeHTML(n.children, i)}
</li>`).join('')}
</ul>`
: '';
document.body.insertAdjacentHTML('beforeend', createTreeHTML(data));
function createTree(data, defaultId, parentIds = '') {
const ul = document.createElement("ul");
data.map((item, index) => {
const li = document.createElement("li");
const id = [parentIds, item.id].join('_')
li.textContent = id;
if (item.children) {
li.appendChild(createTree(item.children, index, id));
}
ul.appendChild(li);
});
return ul;
}