0

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!

Community
  • 1
  • 1

2 Answers2

1

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;
  });
});
Community
  • 1
  • 1
0

The function below builds a tree from a list of objects. It’s not tight to any format. The only difference with your example is that you provide the parent key, not the child.

function buildTree(flatList, idFieldName, parentKeyFieldName, fieldNameForChildren) {
    var rootElements = [];
    var lookup = {};

    flatList.forEach(function (flatItem) {
      var itemId = flatItem[idFieldName];
      lookup[itemId] = flatItem;
      flatItem[fieldNameForChildren] = [];
    });

    flatList.forEach(function (flatItem) {
      var parentKey = flatItem[parentKeyFieldName];
      if (parentKey != null) {
        var parentObject = lookup[flatItem[parentKeyFieldName]];
        if(parentObject){
          parentObject[fieldNameForChildren].push(flatItem);
        }else{
          rootElements.push(flatItem);
        }
      } else {
        rootElements.push(flatItem);
      }

    });

    return rootElements;
  }

Here is a fiddle using your example as input.

The original source comes from this answer.

Community
  • 1
  • 1
Andrew
  • 7,848
  • 1
  • 26
  • 24