Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript dot notation with variable

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.

like image 864
Justin Carlson Avatar asked Dec 03 '22 05:12

Justin Carlson


1 Answers

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.

like image 121
Paul Avatar answered Dec 15 '22 16:12

Paul