我有一小段代码,我用它来尝试从平面列表中构建层次结构(准确地说是对象。)
AFAIK 这应该可以工作,但由于某种原因,在列表的最后一项上,findParent 函数返回未定义,即使我在返回之前调用的 console.log 确实给了我正确的值。知道是什么原因造成的吗?
var fl = [{
"pk": 1,
"title": "paul",
"parent": 3,
"level": 2
}, {
"pk": 2,
"title": "ringo",
"parent": null,
"level": 0
}, {
"pk": 3,
"title": "john",
"parent": 2,
"level": 1
}];
var ho = {};
var looplevel = 0;
var found = 0;
function findParent (ho,id){
for (i in ho) {
ob = ho[i];
if (ob.pk === id) {
console.log(ob);
return ob;
}
if (ob.children !== undefined){
findParent(ob.children,id);
}
}
}
while (fl.length != found) {
for (var i in fl) {
var item = fl[i];
if (item.level === looplevel) {
item.children = {};
if (looplevel === 0) {
ho[item.pk] = item;
console.log("adding " + item.title + " to hl");
found += 1;
} else {
console.log("adding " + item.title + " to " + item.parent);
ww = findParent(ho,item.parent);
console.log(ww);
ww.children[item.pk] = item;
found += 1;
}
looplevel += 1;
}
}
}
console.log(ho);