I want to get the value of a property of a local object variable by using it's "fully qualified" variable name.
function foo() {
var obj = {
prop: "val"
}
var valueStr = "obj.prop";
var value = // code here that gets value using valueStr
}
I have seen this answer for getting a global variable from a string, and I have seen this other answer for getting a property from an object using a string, but what is the simplest way to get both the object AND the property of that object all from a string? I don't want my object to have to be global.
Here is what I'm currently doing to solve this, but it requires that the object be made into a global variable.
var valueStrParts = valueStr.split(".");
var value = window[valueStrParts[0]][valueStrParts[1]];
I would prefer not to use eval()
, but I will if I must. However, I need to be able to verify that the string it evaluates is sanitized and won't do anything more than access the property.