JSON树到父链接结构

时间:2012-11-02 18:59:52

标签: javascript tree

我有一个JSON树结构:

nodes = 
[
{
    "name": "user1",
    "children": [
        {
            "name": "user2"
        },
        {
            "name": "user3",
            "children": [
                {
                    "name": "user4"
                }
            ]
        },
        {
            "name": "user5"
        }
    ]
}
]

我想转换为父链接结构:

[{"name": "user1","parent": "null"},
 {"name": "user2","parent": "user1"},
 {"name": "user3","parent": "user1"},
 {"name": "user4","parent": "user3"},
 {"name": "user5","parent": "user1"}]

我试图以递归方式遍历树,但没有成功访问父对象:

rebuild(nodes,parentLink);

function parentlink(key,value) {
    var obj = { name: value , parent: ??? };
    if (key == "name"){
        nodes.push(obj);
    }
}

function rebuild(o,func) {
    for (i in o) {
        func.apply(this,[i,o[i]])
      if (typeof(o[i])=="object") {
        traverse(o[i],func,nodes);
      }
    }
}

在开发人员工具中,我可以看到每个孩子的父对象,但我不知道如何访问它们。如何将父级添加到每个用户?

1 个答案:

答案 0 :(得分:2)

我不会撒谎,我不打扰看你的代码 - 我就是这样做的:

http://jsfiddle.net/J6G2W/1/

function processChildren(item, ret, parent) {
    for (var i = 0; i < item.length; i++) {
        var cur = item[i];
        var cur_name = cur.name;
        ret.push({"user": cur_name, "parent": parent});
        if ("children" in cur && cur.children.length > 0) {
            processChildren(cur.children, ret, cur_name);
        }
    }
}

var all = [];

processChildren(nodes, all, null);

console.log(JSON.stringify(all));

输出是:

[{"user":"user1","parent":null},{"user":"user2","parent":"user1"},{"user":"user3","parent":"user1"},{"user":"user4","parent":"user3"},{"user":"user5","parent":"user1"}]

这似乎是你正在寻找的。我们欢迎您修改我的代码,使其更像您的代码,我只是觉得我会分享我的所作所为:)

<强>更新

如果由于某种原因,您希望使其更具扩展性,您可以自定义哪些键是“名称”,哪些键是“子”...例如:

http://jsfiddle.net/J6G2W/2/

function startProcess(item, ret, key_look, children_look, parent) {
    function processChildren(item2, ret2, parent2) {
        for (var i = 0; i < item2.length; i++) {
            var cur = item2[i];
            var cur_name = key_look in cur ? cur[key_look] : null;

            ret.push({"user": cur_name, "parent": parent2});
            if (children_look in cur && cur[children_look].length > 0) {
                processChildren(cur[children_look], ret, cur_name);
            }
        }
    }

    processChildren(item, ret, parent);
}

var all = [];

startProcess(nodes, all, "name", "children", null);

console.log(JSON.stringify(all));

注意你只需要指定key_look, children_look个参数一次。内部函数可以访问这些参数,同时只传递每次递归的重要事物。这可能并不重要,我只是想弄明白:)