У вас что сообщения в файлике хранятся что-ли?
var items = [
{
"Id": "1",
"Name": "q",
"Parent": "2"
},
{
"Id": "2",
"Name": "w",
"Parent": ""
},
{
"Id": "3",
"Name": "e",
"Parent": "5"
},
{
"Id": "4",
"Name": "r",
"Parent": "2"
},
{
"Id": "5",
"Name": "t",
"Parent": ""
},
{
"Id": "6",
"Name": "y",
"Parent": "2"
},
{
"Id": "7",
"Name": "u",
"Parent": "6"
},
{
"Id": "8",
"Name": "i",
"Parent": "6"
}
];
var items = [
{
"Id": "1",
"Name": "q",
"Parent": "2"
},
{
"Id": "2",
"Name": "w",
"Parent": ""
},
{
"Id": "3",
"Name": "e",
"Parent": "5"
},
{
"Id": "4",
"Name": "r",
"Parent": "2"
},
{
"Id": "5",
"Name": "t",
"Parent": ""
},
{
"Id": "6",
"Name": "y",
"Parent": "2"
},
{
"Id": "7",
"Name": "u",
"Parent": "6"
},
{
"Id": "8",
"Name": "i",
"Parent": "6"
}
];
function buildHierarchy(arry) {
var roots = [], children = {};
// find the top level nodes and hash the children based on parent
for (var i = 0, len = arry.length; i < len; ++i) {
var item = arry[i],
p = item.Parent,
target = !p ? roots : (children[p] || (children[p] = []));
target.push({
value: item
});
}
// function to recursively build the tree
var findChildren = function (parent) {
if (children[parent.value.Id]) {
parent.children = children[parent.value.Id];
for (var i = 0, len = parent.children.length; i < len; ++i) {
findChildren(parent.children[i]);
}
}
};
// enumerate through to handle the case where there are multiple roots
for (var i = 0, len = roots.length; i < len; ++i) {
findChildren(roots[i]);
}
return roots;
}
console.log(buildHierarchy(items));
var items = [
{
"Id": "1",
"Name": "q",
"Parent": "2"
},
{
"Id": "2",
"Name": "w",
"Parent": ""
},
{
"Id": "3",
"Name": "e",
"Parent": "5"
},
{
"Id": "4",
"Name": "r",
"Parent": "2"
},
{
"Id": "5",
"Name": "t",
"Parent": ""
},
{
"Id": "6",
"Name": "y",
"Parent": "2"
},
{
"Id": "7",
"Name": "u",
"Parent": "6"
},
{
"Id": "8",
"Name": "i",
"Parent": "6"
}
];
function buildHierarchy(arry) {
var roots = [], children = {};
// find the top level nodes and hash the children based on parent
for (var i = 0, len = arry.length; i < len; ++i) {
var item = arry[i],
p = item.Parent,
target = !p ? roots : (children[p] || (children[p] = []));
target.push({
value: item
});
}
// function to recursively build the tree
var findChildren = function (parent) {
if (children[parent.value.Id]) {
parent.children = children[parent.value.Id];
for (var i = 0, len = parent.children.length; i < len; ++i) {
findChildren(parent.children[i]);
}
}
};
// enumerate through to handle the case where there are multiple roots
for (var i = 0, len = roots.length; i < len; ++i) {
findChildren(roots[i]);
}
return roots;
}
console.log(buildHierarchy(items));
так я нашла этот код там. проверила))) работает. подставила свои комментарии и в консоль все выводит.
но теперь надо в html это впихнуть. а вот как создавать ul li в такой ситуации я не знаю.
https://github.com/typicode/json-server
самый простой сервер)