dmathisen dmathisen - 8 months ago 19
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
from a parameter in the URL - it comes in as a string...

var obj = "objectTwo";

How can I access
using this

I can't do the below because
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?


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.