Zkoušel jsem to dát celý do objektu abych to trochu odlišil od jiného kódu ale stejně to nefunguje.
var obj = {
items: [{
id: 45,
lable: "Test 1.2.1",
parent_id: 2
}, {
id: 12,
lable: "Test 1.0",
parent_id: 0
}, {
id: 32,
lable: "Test 1.1",
parent_id: 12
}, {
id: 2,
lable: "Test 1.2",
parent_id: 12
}]
},
objDict : this.items.reduce(function(p, c) {
p[c.id] = c;
c.children = [];
return p;
}, {}),
tree : this.items.reduce(function(p, c) {
if (!c.parent_id) {
p = c;
} else {
this.objDict[c.parent_id].children.push(c);
}
return p;
}, {}),
processTree : function (node, element) {
var li = document.createElement('li');
li.innerText = node.lable;
element.appendChild(li);
if (node.children.length) {
var ul = document.createElement('ul');
li.appendChild(ul);
for (var i = 0; i < node.children.length; i++) {
this.processTree(node.children[i], ul);
}
}
}
obj.processTree(this.tree, document.getElementById("list"));