How can I retrieve the value of a property from a local object variable using its fully qualified variable name?
function foo() {
var obj = {
prop: "val"
}
var valueStr = "obj.prop";
var value = // code here that gets value using valueStr
}
I've come across this solution for accessing global variables dynamically by their names as strings, and also found this other approach for getting an object property using a string. However, I am looking for a simple way to obtain both the object and its property solely based on a string. I want to avoid making my object a global variable.
My current workaround involves turning the object into a global variable, like this:
var valueStrParts = valueStr.split(".");
var value = window[valueStrParts[0]][valueStrParts[1]];
I would rather not resort to using eval()
, but I'm open to it if necessary. Nonetheless, I need to ensure that the evaluated string is sanitized and will only access the specified property without executing any harmful commands.