JSFiddle - React, Tailwind, and code Playground
by jrab227
JavaScript
var organizations = [{
id: 1,
parentId: 2
}, {
id: 3,
parentId: 2
}, {
id: 5,
parentId: 2
}, {
id: 6,
parentId: 0
}, {
id: 4,
parentId: 5
}, {
id: 2,
}, {
id: 0
}];
var organizationsHash = organizations.reduce(function(agg, next) {
agg[next.id] = next;
return agg;
}, {});
var organizationsTree = organizations.reduce(function(tree, next) {
if (next.parentId !== null) {
if (!organizationsHash[next.parentId].children) {
organizationsHash[next.parentId].children = [next];
} else {
organizationsHash[next.parentId].children.push(next);
}
}
return organizationsHash;
}, organizationsHash);
console.log(organizationsTree);