1

我有一个 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);
      }
    }
}

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

4

1 回答 1

3

我不会撒谎,我没有费心看你的代码——我会这样做:

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一次参数。内部函数可以访问这些参数,同时每次递归只传递重要的东西。这可能并不重要,我只是想弄清楚:)

于 2012-11-02T19:16:05.640 回答