我有一个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,但我无法成功实现它们。
答案 0 :(得分: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);