4

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).

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

I have access to the 'data' variable, 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 travel to the root

target = data

then 1 level deep

target = data['level1'] 

...keep going

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

and modify the contents

target = 'hey'

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

I guess I can build a string with the path and then evaluate it:

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

Is there a better solution that dosen't involve eval()?

1
  • "...lose the reference to the original object" then don't...keep a variable pointing to the original data object Commented Aug 20, 2012 at 6:54

2 Answers 2

4

There are two issues. First is that you keep using data inside the loop, which means you're trying to access the top level keys instead of the inner keys. Change target = data[parents[i]]; to

target = target[parents[i]];

The second is that when you change the variable target, you're not changing the data variable but target instead. If you drop out of the loop one iteration earlier you can update the object which is stored as a reference:

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

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

Sign up to request clarification or add additional context in comments.

Comments

1

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: I was missing something (sorry, should have tested it first..)

2 Comments

That's what I posted, no? console.log(data.level1.level2) outputs 'hello' instead of 'hey'.
Changing the target variable doesn't update the data object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.