2

I need to reference my object as a string but I am having issues.

ideally I would like this to work ['mystring'].myproperty; but obviously this wont work.

Is there another way besides the options below?

// auto generated ecample/////////////

var mystring = {
myproperty :'test'

}
/////////////////////////////////////

var optionA =mystring.myproperty; // works


var optionB = window['mystring'].myproperty; //gives issues


var optionC = eval('mystring').myproperty; //gives issues


var optionD = ['mystring'].myproperty; // wont work
7
  • optionC no use; overkill. optionD you're creating an array with one string inside, and the array doesn't have a myproperty method. So use A or B, those are correct. Commented Nov 11, 2013 at 9:14
  • 1
    mystring is not property of the window object Commented Nov 11, 2013 at 9:14
  • I've used B and I've had issues, also want to find a way to do this. OP wants to use e.g. var x = "mystring"; alert(x.myproperty); Commented Nov 11, 2013 at 9:16
  • 8
    If you don't create all global variables you entirely avoid this issue. var MY = { mystring: { myproperty: 'test' } }; MY['mystring'].myproperty Commented Nov 11, 2013 at 9:17
  • thanks, change it to answer and I'll mark it Commented Nov 11, 2013 at 9:39

1 Answer 1

0

If your variables are defined on a global scope, the following works

window[ mystring.myproperty ].data

If you are in a function's scope, things get a lot harder. Easiest way then is to define your objects in a specific namespace on window and retrieve the objects similar to the above code.

Sign up to request clarification or add additional context in comments.

1 Comment

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.