Skip to content
Advertisement

how to get an updated copy of a node tree after removing some of its nodes?

I need based on a condition to remove a node from a tree nodes and obtain as a result an updated copy of the tree nodes

With the help of this answer https://stackoverflow.com/a/72121755/615274 I get to the node to delete, I exclude it from the array it belongs to but the returned node tree does not reflect the changes

The data is as follows

JavaScript

The logic I use now is the following

JavaScript

This identifies the node to delete, excludes it from it container, but when returning the node tree, the modification is not reflected.

JavaScript

Thanks in advance

Advertisement

Answer

I regularly use variants of a deepFilter function, which lets us build a non-mutating version of this very easily:

JavaScript
JavaScript

deepFilter tests a given predicate function against each of your input values, and recursively against their children. If it returns true for the value or for any of its children, we keep that value in the result. If not, we skip it.

That lets us write a trivial deleteNode function, simply by testing whether the node’s data property is different from our target value.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement