1

If I have a javascript object like this...

window.object = 
{
    "Element1" :
    {
        "startDate" : "-1m",
        "endDate" : "0d"
    }
};

I can use the below code to alert out -1m...

alert(object.Element1.startDate);

However, what if Element1 was given to me through a parameter as a string. How could I get the same result if I have to use a variable? Like this but not correct...

var elementId = this.id;
alert(object.elementId.startDate);
gmustudent
  • 2,229
  • 6
  • 31
  • 43

2 Answers2

5

Try this:

object[elementId].startDate

Or if id is a number , this will work:

object["Element"+elementId].startDate
Ivan Chernykh
  • 41,617
  • 13
  • 134
  • 146
1

You can use the global object this:

var Element1 = 'boo';

var stringname = 'Element1';
alert(this[stringname]);

A second, hacky, method, is that javascript can print javascript and that printed javascript will also be interpreted.

neonKow
  • 29
  • 4
  • If you use `window` instead of `this`, you can access global variables everywhere not only in global scope. What do you mean by *"javascript can print javascript and that printed javascript will also be interpreted"*? Could you provide an example? – Felix Kling Sep 09 '13 at 19:30
  • If you do `document.write('alert("boo");');`, it will give you an alert. Breaking up the script tag may or may not be necessary depending on context, I believe. – neonKow Sep 09 '13 at 20:19