我正在设置构建树函数。一切正常,直到我添加一个 parentID 不存在的文档。根节点也应该是最小的 paarentID。即使 parentID 不是“0”。我不知道我做错了什么。
我试图在某处添加一个 if 子句,但没有成功。
function list_to_tree(list) {
var map = {},
node,
roots = [],
i;
for (i = 0; i < list.length; i += 1) {
map[list[i]._id] = i; // initialize the map
list[i].children = []; // initialize the children
list[i].link = []; // initialize the link field
}
for (i = 0; i < list.length; i += 1) {
node = list[i];
if (node._source.parentID !== '0') {
list[map[node._source.parentID]].children.push(node);
} else {
roots.push(node);
}
}
return roots;
}
var entries = [
{
"_index": "fud_alvr",
"_type": "analyse",
"_id": "10",
"_score": 1.4142135,
"_source": {
"ID": "10",
"parentID": "0",
"content": "Europa"
}
},
{
"_index": "fud_alvr",
"_type": "analyse",
"_id": "22",
"_score": 1.4142135,
"_source": {
"ID": "22",
"parentID": "10",
"content": "Germany"
}
},
{
"_index": "fud_alvr",
"_type": "analyse",
"_id": "23",
"_score": 1.4142135,
"_source": {
"ID": "23",
"parentID": "90",
"content": "Switzerland"
}
},
{
"_index": "fud_alvr",
"_type": "analyse",
"_id": "438",
"_score": 1.4142135,
"_source": {
"ID": "438",
"parentID": "22",
"content": "München"
}
}
];
console.log(list_to_tree(entries));
错误信息是:TypeError: 无法读取未定义的属性“children”
如果我删除瑞士,一切正常。
最佳答案
您可以检查父级是否存在,如果不存在,则将 '0'
指定为 parentID
。
function list_to_tree(list) {
var map = {},
node,
roots = [],
i;
for (i = 0; i < list.length; i += 1) {
map[list[i]._id] = i; // initialize the map
list[i].children = []; // initialize the children
list[i].link = []; // initialize the link field
}
for (i = 0; i < list.length; i += 1) {
node = list[i];
// check if parent exists
if (!(node._source.parentID in map)) node._source.parentID = '0';
if (node._source.parentID !== '0') {
list[map[node._source.parentID]].children.push(node);
} else {
roots.push(node);
}
}
return roots;
}
var entries = [{ _index: "fud_alvr", _type: "analyse", _id: "10", _score: 1.4142135, _source: { ID: "10", parentID: "0", content: "Europa" } }, { _index: "fud_alvr", _type: "analyse", _id: "22", _score: 1.4142135, _source: { ID: "22", parentID: "10", content: "Germany" } }, { _index: "fud_alvr", _type: "analyse", _id: "23", _score: 1.4142135, _source: { ID: "23", parentID: "90", content: "Switzerland" } }, { _index: "fud_alvr", _type: "analyse", _id: "438", _score: 1.4142135, _source: { ID: "438", parentID: "22", content: "München" } }];
console.log(list_to_tree(entries));
关于javascript - 如何修复我的建筑树功能。如果 parent ID 不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57452082/