I'm converting a flat hierarchy of objects into nested objects based on parent node ids.
The problem is that when I input more complex structures (more and deeper children), the process takes a really long time to finish.
Maybe it's related to memory or other inefficient use of recursion or redundancy? I'm not sure.
The code:
const people = [
{
id: '738a8f8a',
parentNode: null
},
{
id: 'd18fd69c',
parentNode: '738a8f8a'
},
{
id: 'b507c11d',
parentNode: '738a8f8a'
},
{
id: '171d4709',
parentNode: 'b507c11d'
},
{
id: '471b1cee',
parentNode: 'b507c11d'
}
];
function getBase(base) {
for (const person of base) {
if (person['parentNode'] === null) {
return person;
}
}
return null;
}
function getChildren(parent) {
const values = people.filter((person) => {
return person['parentNode'] === parent['id'];
});
return Object.values(values);
}
function buildHierarchy(base = null) {
if (base === null) {
base = getBase(people);
if (base === null) {
return null;
}
}
const children = getChildren(base).map((child) => {
return buildHierarchy(child);
});
base['childrenNodes'] = children;
return base;
}
console.log(buildHierarchy());
And the output of the console.log above:
{
id: '738a8f8a',
parentNode: null
childrenNodes: [
{
id: 'd18fd69c',
parentNode: '738a8f8a',
childrenNodes: [],
},
{
id: 'b507c11d',
parentNode: '738a8f8a',
childrenNodes: [
{
id: '171d4709',
parentNode: 'b507c11d',
childrenNodes: [],
},
{
id: '471b1cee',
parentNode: 'b507c11d',
childrenNodes: [],
},
],
},
],
};