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");