I need to create function which will be able to convert flat object to recursive object. Here is my example: I have flat array:
var flatArray = [
{
I tried to write the algorithm in pseudocode, ended up with JS code that almost works (perhaps some additional validations/checks are needed) but shows the general approach to the problem.
//Lets separate children (nodes with a parent) from roots (nodes without a parent)
var children = flatArray.filter(function(object){
return object.parent !== null;
});
var roots = flatArray.filter(function(object){
return object.parent === null;
});
//And add each child to the nodes tree
children.foreach(function(child){
recursiveAdd(roots, child);
});
//To add a children node, node tree is searched recursively for a parent
function recursiveAdd(nodes, child){
nodes.foreach(function(parent){
if(parent.guid === child.parent){
parent.Children = parent.Children | [];
parent.Children.add(child);
} else if(parent.Children) {
recursiveAdd(parent.Children, child);
}
});
}
//Temporary children array can be garbage collected
children = null;
//Resulting node tree
var recursiveArray = roots;