{id: 1, name: "Категория 1", parent_id: 0}
{id: 2, name: "Категория 2", parent_id: 0}
{id: 3, name: "Категория 3", parent_id: 1}
function createTreeData(arr, idProp, parentProp) {
const tree = Object.fromEntries(arr.map(n => [ n[idProp], { ...n, children: [] } ]));
return Object.values(tree).filter(n => !tree[n[parentProp]]?.children.push(n));
}
const createTreeHTML = data =>
Array.isArray(data) && data.length
? `<ul>${data.map(n => `
<li>
${n.name}
${createTreeHTML(n.children)}
</li>`).join('')}
</ul>`
: '';
const treeData = createTreeData(data, 'id', 'parent_id');
const treeHTML = createTreeHTML(treeData);
treeContainerElement.innerHTML = treeHTML;