dmathisen dmathisen - 5 months ago 7
Javascript Question

Accessing a JavaScript object using a string

I have a few simple objects defined...

var objectOne = {
settings: {
name: "object one"
}
}

var objectTwo = {
settings: {
name: "object two"
}
}


Now let's pretend I got
object
from a parameter in the URL - it comes in as a string...

var obj = "objectTwo";


How can I access
objectTwo.settings
using this
obj
variable?

I can't do the below because
obj
is a string:

var settings1 = obj.settings;
var settings2 = [obj].settings; // also doesn't work


I tried stripping the quotes without any luck.

How can I access a top level object using a string?

Answer

If it is in the global namespace you could use window[obj].settings.

If not, I don't think there is much you can do except eval as @MikeC mentioned in comments, which is rarely a good idea.

Comments