将json对象排序为嵌套树

时间:2013-07-09 17:41:43

标签: javascript jquery sorting tree

我从网络服务中提取两个相关对象 - 文件夹和电子邮件。文件夹具有ID和parentfolder.ID属性,该属性指示文件夹嵌套在哪个父文件夹下。电子邮件有一个CategoryID,表示它是哪个文件夹。

我已经成功创建了一个将电子邮件嵌套在平面文件夹结构中的功能:

{
"folders": [
    {
        "name": "my emails",
        "type": "folder",
        "additionalParameters": {
            "id": "174661",
            "type": "email",
            "parentID": "0"
        },
        "children": [
            {
                "name": "Test1",
                "type": "item",
                "additionalParameters": {
                    "id": "27502",
                    "subject": "Test"
                }
            },
            {
                "name": "Hello",
                "type": "item",
                "additionalParameters": {
                    "id": "27917",
                    "subject": "Hi!"
                }
            }
        ]
    },
    {
        "name": "Test",
        "type": "folder",
        "additionalParameters": {
            "id": "175620",
            "type": "email",
            "parentID": "174661"
        },
        "children": [
            {
                "name": "Test2",
                "type": "item",
                "additionalParameters": {
                    "id": "27891",
                    "subject": "Test"
                }
            }
        ]
    },
    {
        "name": "SubFolder1",
        "type": "folder",
        "additionalParameters": {
            "id": "175621",
            "type": "email",
            "parentID": "175620"
        },
        "children": [
            {
                "name": "Test2",
                "type": "item",
                "additionalParameters": {
                    "id": "27892",
                    "subject": "Test"
                }
            },
            {
                "name": "Test3",
                "type": "item",
                "additionalParameters": {
                    "id": "27893",
                    "subject": "Test"
                }
            }
        ]
    },
    {
        "name": "SubFolder2",
        "type": "folder",
        "additionalParameters": {
            "id": "175622",
            "type": "email",
            "parentID": "175620"
        },
        "children": [
            {
                "name": "Test4",
                "type": "item",
                "additionalParameters": {
                    "id": "27894",
                    "subject": "Test"
                }
            }
        ]
    }
]
}

现在我需要使用递归遍历所有文件夹并将它们推送到其父级的 children 数组中。基本上将树木移至n级。我可以忽略任何 type = items ,因为它们已经被适当地嵌套了。只需要对那些类型为文件夹的人进行排序。

是否有人实现了JSON递归函数来重建嵌套的JSON对象?

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

您可以在没有递归的情况下执行此操作。某个时候我回答了similar question。我相信你可以使用相同的方法(假设你没有前向引用):

var idToNodeMap = {}; //Keeps track of nodes using id as key, for fast lookup
var root = null; //Initially set our root to null

//loop over data
for(var i = 0; i < data.folders.length; i++) {
    var folder = data.folders[i];

    //each node will have children, so let's give it a "children" poperty
    folder.children = [];

    //add an entry for this node to the map so that any future children can
    //lookup the parent
    idToNodeMap[folder.additionalParameters.id] = folder;

    //Does this node have a parent?
    if(folder.additionalParamters.parentID === "0") {
        //Doesn't look like it, so this node is the root of the tree
        root = folder;        
    } else {        
        //This node has a parent, so let's look it up using the id
        parentNode = idToNodeMap[folder.additionalParamters.parentID];    

        //Let's add the current node as a child of the parent node.
        parentNode.children.push(folder);        
    }
}

答案 1 :(得分:0)

感谢Vivin。通过他的回答,我找到了一种最终起作用的方法的链接。这是最终的代码:

var arr = $this.folderArray;
                        // Define root
                        console.log("arr");
                        console.log(arr);

                        // Define tree
                        var tree = {
                            root: root
                        };
                        console.log('tree');
                        console.log(tree);
                        // Get parent of node (recursive)
                        var getParent = function (rootNode, rootId) {
                            console.log('rootnode');
                            console.log(rootNode);
                            console.log('rootId');
                            console.log(rootId);
                            if (rootNode.additionalParameters.id === rootId)
                                return rootNode;

                            for (var i = 0; i < rootNode.children.length; i++) {
                                var child = rootNode.children[i];
                                if (child.additionalParameters.id === rootId) return child;

                                if(child.children){
                                    if (child.children.length > 0){
                                        var childResult = getParent(child, rootId);
                                        if (childResult != null) return childResult;
                                    }
                                }

                            }
                            return null;
                        };


                        // Traverse data and build the tree
                        var buildTree = function(tree) {
                            for (var i = 0; i < arr.length; i++) {
                                var elem = arr[i];
                                if (elem.additionalParameters.parentID === "0")
                                    continue;
                                //elem["children"] = [];

                                var rootId = elem.additionalParameters.parentID;
                                var parent = getParent(tree.root, rootId);
                                console.log("parent");
                                console.log(parent);
                                parent.children.push(elem);

                                // Debug info
                               // console.log("Elem: " + elem.name + " with parent_id: " + elem.parentAreaRef.id);
                                //console.log("Got parent with name: " + parent._id);
                            }
                        };
                        buildTree(tree);