2๐
โ
You could do this with two functions one to create nested tree structure and another one to create a nested html structure based on previously create tree structure.
let data = [{id: 3, name: ''}, {id: 4, name: ''}, {id: 5, name: '', parent: 3}, {id: 6, name: '', parent: 5}, {id: 7, name: '', parent: 4}, {id: 8, name: '', parent: 8}];
const toTree = (data, pid = undefined) => {
return data.reduce((r, e) => {
if (pid == e.parent) {
const obj = { ...e }
const children = toTree(data, e.id);
if (children) obj.children = children
r.push(obj)
}
return r
}, [])
}
const toHtml = (data) => {
const ul = document.createElement('ul')
data.forEach(e => {
const li = document.createElement('li');
const text = document.createElement('span')
text.textContent = `object id: ${e.id}`;
li.appendChild(text)
const children = toHtml(e.children);
if (children) li.appendChild(children)
ul.appendChild(li)
})
return ul
}
const tree = toTree(data)
const html = toHtml(tree)
document.body.appendChild(html)
Source:stackexchange.com