How to get altered tree from Immutable tree, maximising reuse of nodes
<p>I have a tree structure data like this:</p>

<pre><code>[{
    id: 54,
    name:123,
    children: [{
        id: 54,
        name:123,
        children: [{
            id: 154,
            name:1234,
            children []...
        }]
    }]
}, {
 ...
}]
</code></pre>

<p>I am using Angular 2. As far as I know, change detection kicks in whenever input changes and your change detection strategy is <a href="https://angular-2-training-book.rangle.io/handout/change-detection/change_detection_strategy_onpush.html" rel="noreferrer"><code>onPush</code></a>.</p>

<p>To optimise the tree structure updates (e.g. toggling a node at a nested level or changing any attributes of such a node), I used <a href="https://facebook.github.io/immutable-js/" rel="noreferrer">Immutable</a>.</p>

<p>How can <strong>Immutable</strong> help me to optimise my updates? I read that <strong>Immutable</strong> reuses references from old data to construct new objects whenever data changes.</p>

<p>How do I use <strong>Immutable</strong> data structures efficiently to update nodes at a nested level?</p>

<h3>Assumptions</h3>

<ol>
<li>I don't have a <code>keyPath</code> for any of the nodes. </li>
<li>Each node has a unique <code>id</code> property value which can be used to query tree data (but how?)</li>
</ol>

<h3>Problems</h3>

<ol>
<li>How can I update a node somewhere at a nested level? What could be the most efficient way of reaching out to that node?</li>
<li>How do I update multiple nodes? I heard of the <code>withMutations</code> API, but is there any other efficient way?</li>
</ol>

<h3>My approach</h3>

<ol>
<li><p>Deep-copy everything and then modify the newly constructed object:</p>

<pre><code>var newState = deepClone(oldState) // deep copy everything and construct a new object 
newState.nodes.forEach(node =&gt; {
    if(node.id == 54) {
        node.id = 789;
    }
})
</code></pre></li>
<li><p>What I am trying to implement:</p>

<pre><code>var newState = Immutable.fromJS(oldState) // create an immutable object 
newState = newState.find(node =&gt; {
    node.set("id", 123);
}); // any changes to object will return new object
</code></pre></li>
</ol>

<p>With the second solution I hope to achieve re-use of nodes, as pictured below:</p>

<p><a href="https://i.stack.imgur.com/uGHcx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/uGHcx.png" alt="Tree view in immutablejs"></a></p>