James Hall
James Hall

Reputation: 35

Javascript objects: use a variable's value to access a specific object

I have multiple objects with identical properties:

var obj1 = { bar: "value1", foo: "value2"};
var obj2 = { bar: "value3", foo: "value4"};

I also have a variable.

var selector = "";

selector is either "obj1" or "obj2". How can I call one of the objects using selector without knowing the object's name?

For instance, I tried:

window(["selector"][bar])

Any help is appreciated! :)

Upvotes: 0

Views: 43

Answers (1)

lightshadowninja
lightshadowninja

Reputation: 71

You have parenthesis. window is not a function. Try without the parenthesis. In addition, you need to put quotes around bar.

window[selector]["bar"]

Upvotes: 2

Related Questions