0

我有一小段代码,我用它来尝试从平面列表中构建层次结构(准确地说是对象。)

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);
4

1 回答 1

3
function findParent (ho,id){
    for (var i in ho) {
        var ob = ho[i];

        if (ob.pk === id) {
            console.log(ob);
            return ob;
        }
        if (ob.children !== undefined){
            var parent = findParent(ob.children,id); 
            if(parent) {//if our recursion found a parent
                return parent;
            }
        }
    }
}

问题是您没有返回递归值。

更新必须查看父母是否存在,这样您就不会提前离开循环

更新 2只是重新阅读您的代码和变量iob并且将是全局的,我更正了我对这个变量的答案

于 2013-10-26T18:05:51.533 回答