3

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'
    }
};

1 Answer 1

2

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

That did it! I'll mark it as answered as soon as it lets me. Thanks!

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.