Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

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);
share|improve this question

marked as duplicate by Felix Kling, maerics, Sirko, Fabio Antunes, Kevin Reid Apr 18 at 17:50

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
whats the format of the string? –  Bob Sinclar Sep 9 '13 at 19:12
    
and Dynamic object property name –  Felix Kling Sep 9 '13 at 19:12

2 Answers 2

up vote 5 down vote accepted

Try this:

object[elementId].startDate

Or if id is a number , this will work:

object["Element"+elementId].startDate
share|improve this answer
    
your first answer captures all cases –  Yaw Sep 9 '13 at 19:14
    
Console is catching an error, object[elementId] is undefined –  gmustudent Sep 9 '13 at 19:16
    
@gmustudent so something wrong with your this.id and as result after this part: var elementId = this.id; your elementId is undefined –  Cherniv Sep 9 '13 at 19:18
    
Sorry. unrelated issue to why I had a problem. Will accept after time limit –  gmustudent Sep 9 '13 at 19:22
    
@gmustudent no problem, glad it works!. –  Cherniv Sep 9 '13 at 19:22

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.

share|improve this answer
    
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 9 '13 at 19:30
    
If you do document.write('<scrip' + 't>alert("boo");</scrip' + 't>');, it will give you an alert. Breaking up the script tag may or may not be necessary depending on context, I believe. –  neonKow Sep 9 '13 at 20:19

Not the answer you're looking for? Browse other questions tagged or ask your own question.