Skip to content Skip to sidebar Skip to footer

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 fie

Solution 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;
  });
});

Solution 2:

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.

functionbuildTree(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.

Post a Comment for "Construct Hierarchy Tree From Flat List With Child Field?"