JSFiddle - React, Tailwind, and code Playground
by Nalin Sajwan
JavaScript
var flatArray = [
{
Description: "G",
guid: "c8e63b35",
parent: null,
},
{
Description: "Z",
guid: "b1113b35",
parent: "c8e63b35",
},
{
Description: "F",
guid: "d2cc2233",
parent: "b1113b35",
},
{
Description: "L",
guid: "a24a3b1a",
parent: null,
},
{
Description: "K",
guid: "cd3b11caa",
parent: "a24a3b1a",
},
]
function flatToHierarchy (flat, mapKey) {
var roots = [] // things without parent
// make them accessible by guid on this map
var all = {}
flat.forEach(function(item) {
all[item[mapKey]] = item
})
// connect childrens to its parent, and split roots apart
Object.keys(all).forEach(function (gKey) {
var item = all[gKey]
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
}
console.log(flatToHierarchy(flatArray, "guid"));