Can anyone help converting the following list of parent-child objects:
[ { \"name\":\"root\", \"_id\":\"root_id\", }, { \"name\":\"a1\"
I have a solution that works. I can give you hints as far as solving it. The good thing is that your data doesn't contain any forward references to nodes. So you can create your tree with just one pass through the array. If note, you will need to make a pass through the entire array first to build up a map of ids to nodes.
Your algorithm will look like this.
children
property (an array) to this node.children
array).This should help you solve the problem. If you're having specific issues with this algorithm I can point out where the problems are and how to solve it or post the solution and explain how I solved it.
UPDATE
I looked at the solution that you have. You actually don't need recursion for this and you can do this iteratively using the algorithm I described above. You are also modifying the structure in-place, which makes the algorithm more complicated. But you're somewhat on the right track. Here is how I solved it:
var idToNodeMap = {}; //Keeps track of nodes using id as key, for fast lookup
var root = null; //Initially set our loop to null
//loop over data
data.forEach(function(datum) {
//each node will have children, so let's give it a "children" poperty
datum.children = [];
//add an entry for this node to the map so that any future children can
//lookup the parent
idToNodeMap[datum._id] = datum;
//Does this node have a parent?
if(typeof datum.parentAreaRef === "undefined") {
//Doesn't look like it, so this node is the root of the tree
root = datum;
} else {
//This node has a parent, so let's look it up using the id
parentNode = idToNodeMap[datum.parentAreaRef.id];
//We don't need this property, so let's delete it.
delete datum.parentAreaRef;
//Let's add the current node as a child of the parent node.
parentNode.children.push(datum);
}
});
Now root
points to the entire tree.
Fiddle.
For the case where the array of elements is in arbitrary order, you will have to initialize idToNodeMap
first. The rest of the algorithm remains more-or-less the same (except for the line where you store the node in the map; that's not needed because you did it already in the first pass):
var idToNodeMap = data.reduce(function(map, node) {
map[node._id] = node;
return map;
}, {});