var data = [
{
"name":"root",
"_id":"root_id",
},
{
"name":"a1",
"parentAreaRef":{
"id":"root_id",
},
"_id":"a1_id",
},
{
"name":"a2",
"parentAreaRef":{
"id":"a1_id",
},
"_id":"a2_id",
},
{
"name":"a3",
"parentAreaRef":{
"id":"a2_id",
},
"_id":"a3_id",
},
{
"name":"b1",
"parentAreaRef":{
"id":"root_id",
},
"_id":"b1_id",
},
{
"name":"b2",
"parentAreaRef":{
"id":"b1_id",
},
"_id":"b2_id",
},
{
"name":"b3",
"parentAreaRef":{
"id":"b1_id",
},
"_id":"b3_id",
}
];
var buildTree = function(tree, item) {
if (item) { // if item then have parent
for (var i=0; i<tree.length; i++) { // parses the entire tree in order to find the parent
if (String(tree[i]._id) === String(item.parentAreaRef.id)) { // bingo!
tree[i].childs.push(item); // add the child to his parent
break;
}
else buildTree(tree[i].childs, item); // if item doesn't match but tree have childs then parses childs again to find item parent
}
}
else { // if no item then is a root item, multiple root items are supported
var idx = 0;
while (idx < tree.length)
if (tree[idx].parentAreaRef) buildTree(tree, tree.splice(idx, 1)[0]) // if have parent then remove it from the array to relocate it to the right place
else idx++; // if doesn't have parent then is root and move it to the next object
}
}
for (var i=0; i<data.length; i++) { // add childs to every item
data[i].childs = [];
}
buildTree(data);
out(JSON.stringify(data));
function out() {
var args = Array.prototype.slice.call(arguments, 0);
document.getElementById('output').innerHTML += args.join(" ") + "\n";
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.