jqTree - creating tree data from json

2020-07-24 04:10发布

问题:

I'm trying to display a tree using jqTree - http://mbraak.github.com/jqTree

I need help with creating the tree data from JSON.

My JSON data looks like this:

    {
"d" : {
"results": [
    {
        "Title": "Committee A", 
        "ReportsToId": null, 
        "Rank": 1, 
        "Id": 5
    }, 
    {   
        "Title": "Committee B", 
        "ReportsToId": 5, 
        "Rank": 2, 
        "Id": 7
    }, 
    {
        "Title": "Committee C",
        "ReportsToId": 7, 
        "Rank": 3, 
        "Id": 13
    }, 
    {   
        "Title": "Committee D",
        "ReportsToId": 13, 
        "Rank": 4, 
        "Id": 1
    }, 
    {
        "Title": "Committee E",
        "ReportsToId": 13, 
        "Rank": 4, 
        "Id": 3
    }
]
}
}

I want to end up with this:

    var treeData = [
    {
        label: 'Committee A',
        children: [
            {
                label: 'Committee B',
                children: [
                {
                    label: 'Committee C',
                    children: [
                        { label: 'Committee D' },
                        { label: 'Committee E' }
                    ]
                }]
            }
            ]
    }
    ];

回答1:

Here's a solution adapted from http://www.jqwidgets.com/populating-jquery-tree-with-json-data/:

var jqTreeData = function (data) {
        var source = [];
        var items = [];
        // build hierarchical source.
        for (i = 0; i < data.length; i++) {
            var item = data[i];
            var title = item["Title"];
            var reportsToId = item["ReportsToId"];
            var id = item["Id"];

            if (items[reportsToId]) {
                var item =
                {
                    label: title
                };

                if (!items[reportsToId].children) {
                    items[reportsToId].children = [];
                }

                items[reportsToId].children[items[reportsToId].children.length] = item;
                items[id] = item;
            }
            else {
                items[id] =
                {
                    label: title
                };

                source[0] = items[id];
            }
        }
        return source;
    }