Maxim Zhukov Maxim Zhukov - 4 months ago 24
Javascript Question

Construct hierarchy tree from flat list with child field?

I have a list of "page" objects with a child field. This child field references another object in the list. I would like to create a tree hierarchy from this list based on this field.
I have found a solution here but it works only if I have a parent field.Here is what my original list looks like:

[
{
id: 1,
title: 'home',
child: null
},
{
id: 2,
title: 'about',
child: null
},
{
id: 3,
title: 'team',
child: 4
},
{
id: 4,
title: 'company',
child: 2
}
]


I would like to convert it into a tree structure like this:

[
{
id: 1,
title: 'home',
},
{
id: 3,
title: 'team',
children: [
{
id: 4,
title: 'company',
children: {
id: 2,
title: 'about',
}
}
]
]


I was hoping for a reusable function that I can call against an arbitrary list any time. Anyone know of a good way to handle this? Any help or advice would be greatly appreciated!

Answer

Found a solution by using Underscore.js to add parents and then use this solution

_.each(flat, function (o) {
  o.child.forEach(function (childId) {
    _.findWhere(flat, {id: childId}).parent = o.id;
  });
});