Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

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?

question from:https://stackoverflow.com/questions/66063003/flatten-a-tree-into-an-array-in-angular

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...