Adam
Adam

Reputation: 9459

Use variable in javascript object selector

I ran into a problem when dynamically attempting to retrieve an object row based on a variable. What would be a good work around to the following situation?

function getDetails(id) {
    completeID = "event" + id;
    title = eventDetails.completeID.title;
}

var eventDetails = {
    'event1': {
        'title': 'Lisbon Earthquake',
            'content': "Test Content",
    },
        'event2': {
        'title': 'Falling Stars',
            'content': 'Test Content'
    }
};

Upvotes: 3

Views: 713

Answers (1)

MD Sayem Ahmed
MD Sayem Ahmed

Reputation: 29186

Try this in your method -

function getDetails(id) {
    completeID = "event" + id;
    title = eventDetails[completeID].title;
}

as an object property can be accessed using a square bracket notation.

On a side note, in your getDetails function you are declaring your variables without the var keyword (unless they are already defined as globals). This will create them as global variables, and it is considered a very bad practice to use global variables this way. Try to declare them as follows -

function getDetails(id) {
    var completeID = "event" + id,
        title = eventDetails[completeID].title;

    // do whatever you want with the title
}

Upvotes: 2

Related Questions