Not sure how to word this.
I am trying to use a variable to determine how far to drill into an object to return a value.
var target = "level1.level2.var";
var myObject = {
level1: {
level2: {
var: 'value'
}
}
}
var returnVal = myObject.target;
How could this be done? Clearly this won't work. Is it possible some other way?
I figured I would have to maybe explode the target var and then loop for each level, but thought I'd ask to see if there was any easier way I could be overlooking.
You could use this function:
function get_property_from_target(obj, target){
var arr = target.split('.');
for(var i = 0; i < arr.length; i++){
if(obj)
obj = obj[arr[i]];
}
return obj;
}
Then call it like:
get_property_from_target(myObject, target);
I'd rename the function to something better too.
Also please don't name an objects property var
since that is a keyword in Javascript it can be confusing, and I'm not sure that it will always work the way you expect or if it will just cause errors in some browsers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With