Updating Nested Attributes in a JavaScript Object

I want to change hi to hey programmatically, the solution should work with any number of nested elements (I just use 2 levels to simplify it).

var data = {level1: {level2 : 'hello' }}; 

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

I tried to do:

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

The idea was to go to the root

 target = data 

then 1 level of depth

 target = data['level1'] 

... keep going

 target = data['level1']['level2'] //data['level1'] === target 

and change the contents

 target = 'hey' 

But it looks like I'm losing the reference to the source object (data) (target = target ['level2']).

I think I can build a line with a path and then evaluate it:

 eval("data['level1']['level2']='hey'); 

Is there a better solution that is not related to eval ()?

+4
source share
2 answers

There are two questions. First, you continue to use data inside the loop, which means that you are trying to access the top-level keys instead of the internal keys. Change target = data[parents[i]]; on the

 target = target[parents[i]]; 

Secondly, when you change the target variable, you do not change the data variable, but target . If you exit the loop one iteration earlier, you can update the object, which is stored as a link:

 for(var i=0; i<parents.length-1; i++){ target = target[parents[i]]; } target[parents[i]] = 'hey'; 

Demo: http://jsfiddle.net/Lherp/

+4
source

Try something like this:

 var data = {level1: {level2 : 'hello' }}; var parents = 'level1/level2'.split('/'); var target = data; for(var i=0; i < parents.length - 1; i++){ target = target[parents[i]]; } target[parents[i]] = 'hey'; 

Or am I missing something?

edit: Something was missing for me (sorry, you should have checked it first.)

+1
source

All Articles