0

我有一个 JSON 数组具有以下数据结构

"Jobs":
        [
            { "id": "1", "JobTitle": "Engineer", "PID": "null" },
            { "id": "2", "JobTitle": "Project Manager", "PID": "null" },
            { "id": "5", "JobTitle": "Auditing Manager", "PID": "2" },
            { "id": "7", "JobTitle": "Auditor", "PID": "5" },
            { "id": "6", "JobTitle": "QA Manager", "PID": "5" },
            { "id": "3", "JobTitle": "QA", "PID": "6" },
            { "id": "4", "JobTitle": "Business Analyst", "PID": "2" }
        ]

我想使用 Jquery 和 Knockoutjs(可选)编写一个 java 脚本来使用 javascript 和 html 构建团队结构(组织),我有 1000 条记录,我尝试了许多递归循环来处理它,但没有成功。

输出应该是这样的

<ul id="root">
<li>Engineer</li> //since their pid is null, then they are root nodes ( yeah not only root)
<li>Project Manager</li>
   <ul>
   <li>Auditing Manager</li>
   <li>Business Analyst</li>
   </ul>

等等,它应该处理许多级别(深度),有人会建议 DFS 或 BFS 但我无法成功实现它们。

4

1 回答 1

3

半夜了,我累了,但我无法拒绝这个挑战。它可能不是最快的解决方案,但结果很好(http://jsfiddle.net/NbRzB/1/):

function printNode(jobs, tree, id)
{
    var html = '<li>' + jobs[id]['JobTitle'] + '</li>';

    if(tree[id] instanceof Array)
    {
        html += '<li><ul>';

        for(var i=0; i<tree[id].length; i++)
        {
            html += printNode(jobs, tree, tree[id][i]);
        }

        html += '</ul></li>';
    }

    return html;
}

var jobs =
[
    { 'id': '1', 'JobTitle': 'Engineer', 'PID': 'null' },
    { 'id': '2', 'JobTitle': 'Project Manager', 'PID': 'null' },
    { 'id': '5', 'JobTitle': 'Auditing Manager', 'PID': '2' },
    { 'id': '7', 'JobTitle': 'Auditor', 'PID': '5' },
    { 'id': '6', 'JobTitle': 'QA Manager', 'PID': '5' },
    { 'id': '3', 'JobTitle': 'QA', 'PID': '6' },
    { 'id': '4', 'JobTitle': 'Business Analyst', 'PID': '2' }
];

// tmp is used to build a better structure id => { attributes }
var tmp = {};

for(var i=0; i<jobs.length; i++)
{
    tmp[jobs[i]['id']] =
    {
        'JobTitle' : jobs[i]['JobTitle'],
        'PID' : jobs[i]['PID']
    }
}

jobs = tmp;
// end - build better structure

// id => { child_id, child_id, ...}
var tree = {};
// { root_id, root_id, ...}
var root = [];

for(var id in tmp)
{
    // no pid ? it is a root
    if(jobs[id]['PID'] == 'null')
    {
        root.push(id);
    }
    else
    {
        // Add "id" to "jobs[id]['PID']"'s children
        if(tree[jobs[id]['PID']] instanceof Array)
        {
            tree[jobs[id]['PID']].push(id);
        }
        else
        {
            tree[jobs[id]['PID']] = [ id ];
        }
    }
}

// recursive way
var html = '<ul id="root">';

for(var i=0; i<root.length; i++)
{
    html += printNode(jobs, tree, root[i]);
}

html += '</ul>';

// output
$('body').append(html);
于 2012-08-24T03:56:21.120 回答