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 ()?
source share