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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…