0

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! :)

4
  • 4
    window[selector].bar Commented Mar 19, 2017 at 21:30
  • 5
    But you probably shouldn't be doing that; have obj1 and obj2 themselves be properties of one of your own objects rather than the global object. Commented Mar 19, 2017 at 21:31
  • In addition to what @Pointy said, the reason here is that () are used to invoke a method, so by doing window() your script looks for a function called window Commented Mar 19, 2017 at 21:32
  • or just use lodash with it's _.get method that will safely return undefined or default value. example: _.get(window, 'obj1.foo') or _.get(window, 'obj1.baar', null) or var selector = 'obj1.foo'; var value = _.get(window, selector); Commented Mar 19, 2017 at 21:42

1 Answer 1

2

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

window[selector]["bar"]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.