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 = [
{
This one works nicely and is easy to read:
function flatToHierarchy (flat) {
var roots = [] // things without parent
// make them accessible by guid on this map
var all = {}
flat.forEach(function(item) {
all[item.guid] = item
})
// connect childrens to its parent, and split roots apart
Object.keys(all).forEach(function (guid) {
var item = all[guid]
if (item.parent === null) {
roots.push(item)
} else if (item.parent in all) {
var p = all[item.parent]
if (!('Children' in p)) {
p.Children = []
}
p.Children.push(item)
}
})
// done!
return roots
}