Update nested attributes in a JavaScript object
<p>I want to change 'hello' to 'hey' programmatically, the solution should work with any number of nested elements (I just use 2 levels to keep it simple). </p>

<pre><code>var data = {level1: {level2 : 'hello' }};
</code></pre>

<p>I have access to the 'data' variable, the path ('level1/level2') and the new value ('hey').</p>

<p>I tried to do:</p>

<pre><code>var parents = 'level1/level2'.split('/');
var target = data;
for(var i=0; i&lt;parents.length; i++){
   target = data[parents[i]];
}
target = 'hey';
</code></pre>

<p>The idea was to travel to the root </p>

<pre><code>target = data
</code></pre>

<p>then 1 level deep </p>

<pre><code>target = data['level1'] 
</code></pre>

<p>...keep going</p>

<pre><code>target = data['level1']['level2'] //data['level1'] === target
</code></pre>

<p>and modify the contents </p>

<pre><code>target = 'hey'
</code></pre>

<p>But it looks like a lose the reference to the original object (data) when I do (target = target['level2']). </p>

<p>I guess I can build a string with the path and then evaluate it: </p>

<pre><code>eval("data['level1']['level2']='hey');
</code></pre>

<p>Is there a better solution that dosen't involve eval()?</p>
