antoninus96
antoninus96

Reputation: 77

Flatten a tree into an array in Angular

I have created a tree, in Angular, from an array with property like id and parentId, using the following algorithm:

  public setTree(_searchResponses):void{
    let treeSearchResponses: Tree[] = [];
    _searchResponses.map((searchResponse) => {
      let treeNode:Tree = new Tree();
      treeNode.id = searchResponse.codElemento;
      treeNode.parentId = searchResponse.codElementoPadre;
      treeNode.name = searchResponse.codElemento;
      treeNode.isExpanded = true;
      this.nodeCounter++;
      treeSearchResponses.push(treeNode)
    });

    const nest = (items, id = null, link = 'parentId') =>
      items
        .filter(item => item[link] === id)
        .map(item => ({ ...item, children: nest(items, item.id) }));

    this.treeNodes =  nest(treeSearchResponses);
  }

After doing that, I used an angular library to visualize the tree and modify it using drag&drop (for example I could add or remove some elements, or move the elements, etc), so the tree structur (the treeNodes) can change.

Afted doing that I should be able to recreate an array like the one I used to generate the tree, in order to save it.

I tried using foreach or while, but I'm not able to iterate in the tree structure, in order to visit every node, how could I generate a "reverse algorithm" to do that?

Upvotes: 0

Views: 1215

Answers (2)

murgank
murgank

Reputation: 131

Reverse Algorithm for the tree formed by your code.

this.searchResponse = [];
function setSearchResponse(treeNode) {
    if (treeNode == null || treeNode == undefined) {
        return;
    }
    treeNode.forEach(node=>{
        this.searchResponse.push({
            codElemento: node.id,
            codElementoPadre: node.parentId
        })

        if (node.children !== null || node.children !== undefined)
            setSearchResponse(node.children);
    }
    )
}

Upvotes: 1

Andrei
Andrei

Reputation: 11951

tree is a structure that can easilly be traversed by a recursive function. also iterator is a js feature that allows to easilly emit items while traversing anything:

function* treeItems(node: Tree, parentId: string) {
  yield {codElemento: node.id, codElementoPadre: parentId};
  for(let child of node.children) yield* treeItems(child, node.id);
}

// usage
const flatArray = [...treeItems(this.treeNodes)];

Upvotes: 1

Related Questions