dmathisen
dmathisen

Reputation: 2342

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?

Upvotes: 1

Views: 90

Answers (3)

Redu
Redu

Reputation: 26161

Good question. Let's invent an Object method to access the object properties dynamically. Object.prototype.getNestedValue() Regardless how deeply your property is located, it takes a series of arguments in order and gets the desired value for you;

In this particular case it's just one argument;

Object.prototype.getNestedValue = function(...a) {
  return a.length > 1 ? (this[a[0]] !== void 0 && this[a[0]].getNestedValue(...a.slice(1))) : this[a[0]];
};
var objects = {
  objectOne: {
    settings: {
        name: "object one"
    }
  },
  objectTwo: {
    settings: {
        name: "object two"
    }
  }
},
        obj = "objectTwo";
     result = objects.getNestedValue(obj);
console.log(JSON.stringify(result));

You can see getNestedValue() and it's twin setNestedValue() working at here

Upvotes: 1

Paul Abbott
Paul Abbott

Reputation: 7211

window is a neat trick, but could you possibly change your data stricture?

var objects = {
  objectOne: {
    settings: {
        name: "object one"
    }
  },
  objectTwo: {
    settings: {
        name: "object two"
    }
  }
}

var id = "objectOne";
alert(objects[id].settings.name);

Upvotes: 2

jeffjenx
jeffjenx

Reputation: 17467

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.

Upvotes: 1

Related Questions