Dynamic way to use string/array as index of object in javascript I've got a structure of files and folders in a directory structured like the "example_object" I describe below. I also have paths of each of the files as strings. 

So my solution is to split the path into an array, and then use the array to index the object as described in the function below. The length of the array will vary as I don't know how many levels of folders there will be.

Whilst what I've written below works, and I guess is only 4 lines, I see a lot of users get anxious about using "eval". It also seems an indirect method to get the job done. Any improvements/alternate ways to do this?



function change_object_using_path_string(this_object,this_path,new_value){
  var array_as_index = this_path.split("/");    
  array_as_index = "['"+array_as_index.join("']['")+"']";
  var code_to_eval = this_object+array_as_index+"='"+new_value+"'";
  eval(code_to_eval);  
}




The above function is what I'm actually using in my script. The below code reflects the structure of the inputs I would put into the above function:

// NOTE: I'm only inputting "example_object" into 'change_object_using_path_string' as a string to facilitate the eval solution I'm using. I would prefer a solution which directly inputs example_object into the function.



example_object = {
  folder_1_name:{
    folder_2_name:{
      folder_3_name:{
        'file.txt':'this file content'  
      }
    }
  }
}
example_path = "folder_1_name/folder_2_name/folder_3_name/file.txt";

change_object_using_path_string("example_object",example_path,"new content instead");
Yes, it's fairly straightforward to do this without using eval. For example, a statement like obj['a']['b']['c']['d'] = 'value'; can be rewritten as a series of smaller steps:

var temp = obj;
temp = temp['a'];      // member access
temp = temp['b'];      // member access
temp = temp['c'];      // member access
temp['d'] = 'value';   // assignment


Now, it shouldn't be too hard to see how those member access statements can be rolled into a loop, if you have an array of indexes (which you do).



A few other notes:


It's good to see descriptive names, but change_object_using_path_string strikes me as a bit too long and unwieldy. What about something like set_path_value?
You may want to use some more spacing between function parameters (param1,param2 vs param1, param2) and operators (a+b vs a + b). This makes individual parts stand out more, making the code a little easier to read.