Justin Carlson
Justin Carlson

Reputation: 2710

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.

Upvotes: 4

Views: 4050

Answers (5)

Blender
Blender

Reputation: 298156

I can see two ways of doing this:

  • Using eval() (frowned upon, as eval is evil):

    var returnVal = eval('myObject.' + target);
    
  • Using a loop:

    var split = target.split('.');
    var newTarget = myObject;
    
    for (var i = 0; i < split.length; i++) {
        newTarget = newTarget[split[i]];
    }
    

Upvotes: 2

Ry-
Ry-

Reputation: 224904

Easier? Sure, use eval:

var obj = eval('myObject.' + target);

That's not really a serious answer, though. You shouldn't use eval that way in good code. The only other way as far as I know, however, is to loop as you describe:

var items = target.split('.');
var obj = myObject;
var i;

for(i = 0; i < items.length; i++) {
    obj = obj[items[i]];
}

Or, with a regular expression hack:

var obj = myObject;
target.replace(/[^\.]+/g, function(m) {
    obj = obj[m];
});

Regardless, you can now use obj.

Upvotes: 4

Paul
Paul

Reputation: 141839

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.

Upvotes: 10

gen_Eric
gen_Eric

Reputation: 227240

What I would do (maybe not the best, but it'll work), is what you've suggested. Explode the variable, and then go to that level.

var target = "level1.level2.var";
target = target.split('.');

var returnVal = myObject;
for(var i=0,len=target.length; i<len; i++){
    returnVal = returnVal[target[i]];
}

console.log(returnVal); // value

Upvotes: 1

hvgotcodes
hvgotcodes

Reputation: 120188

there is no way, other than writing code to split your target on ., then for each token, drill down into the object as long as the "path" is valid.

Upvotes: 1

Related Questions