miron
miron

Reputation: 1450

Building an recursive tree from another

I have an problem with building an recursive tree from another. The function seems to work but if you expand the first array you'll notice that there is an endless recursion at index 2.

My function which builds the tree:

var buildTree = function(data, idx, aparent){
  var parent = aparent || [];

  for(var i = 0, c = data.length ; i < c ; i++){
    parent.push({
      text: data[i].text,
      items: []
    });


    if(typeof data[i].items !== 'undefined' && data[i].items.length > 0){
      var t = buildTree(data[i].items, idx + 1, parent[parent.length - 1].items);
      parent[parent.length - 1].items.push(t);

    }
  }
  return parent;
};

And that's how my tree data looks like:

[{
  text: "house",
  groupId: "1",
  type: "group",
  items: [{
    text: "basement",
    groupId: "2",
    type: "group"
  },{
    text: "flat-1",
    groupId: "3",
    type: "group",
    items: [{
      text: "computer"
    }]
  }]
},{
  text: "other-house",
  groupId: "4",
  type: "group"
}];

I think i has something to do that javascript returns the value by reference...

Here's a plunk with the complete data, check the console to after clicking the button to get an idea what i mean.

Upvotes: 1

Views: 125

Answers (1)

kaspermoerch
kaspermoerch

Reputation: 16570

I can't really get my head around your code. Maybe your problem has something to do with the fact that you pass in the items-array during your recursion.

I have fixed up your code - making it a bit more simple and easy to read. It relies on the property items being an array if present, so if that is not always the case you need to add error handling for this scenario.

function recursiveBuildTree(data) {
    var result = [];

    data.forEach(function(item) {
      var newItem = {
        text: item.text,
        items: item.items ? recursiveBuildTree(item.items) : []
      };

      result.push(newItem);
    });

    return result;
}

Upvotes: 1

Related Questions