Reputation: 146
i have a JSON array have the following data structure
"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" }
]
i want to write a java script using Jquery and Knockoutjs (optional) to build a team structure (organization) with javascript and html, i have like 1000 record i have tried many recursive loops to handle it with no success.
the out put should be like this
<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>
and so on, it should handle many levels (depth), somebody will suggest DFS or BFS but i couldn't implement them successfully.
Upvotes: 0
Views: 1468
Reputation: 1607
It's midnight, I'm tired, but I can not refuse this challenge. It may not be the fastest solution, but the result is good (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);
Upvotes: 3