Rahul Dagli
Rahul Dagli

Reputation: 4502

Dynamically reference json object using parameters

I'm getting:

Uncaught TypeError: Cannot read property '0' of undefined

While trying to dynamically reference javascript object using parameters. Although when I tried passing single argument virtual_page_no it was working but it started giving error while passing 2 parameters.

// Json list
var patients = {
    "patient_1": [
        {
            "page_no": "3",
            "quest_response_headline": "Question1",
            "quest_response": "Response1",
            "quest_next_link": "View Answer"
        },
        {
            "page_no": "4",
            "quest_response_headline": "Question2",
            "quest_response": "Response2",
            "quest_next_link": "Next Question >"
        }
    ]
}

var current_virtual_page = 0;
var next_virtual_page = current_virtual_page + 1;

function quest_response_text(i, virtual_page_no) {
    var quest_response_headline = patients.patient_i[virtual_page_no].quest_response_headline;
    var quest_response = patients.patient_i[virtual_page_no].quest_response;
    var quest_next_link = patients.patient_i[virtual_page_no].quest_next_link;

    $('.quest-response-headline').text(quest_response_headline);
    $('.quest-response').text(quest_response);
    $('.quest-next-link').text(quest_next_link);
}

// init
quest_response_text(1, current_virtual_page);

// When user click on view answer or next question link
$('.quest-next-link').on('click', function () {
    quest_response_text(next_virtual_page);
});

Upvotes: 1

Views: 243

Answers (1)

hsz
hsz

Reputation: 152256

If you want to dynamically access patients.patient_1 using i variable, try with:

patients['patient_' + i]

so it should looks like:

var quest_response_headline = patients['patient_' + i][virtual_page_no].quest_response_headline;

Upvotes: 1

Related Questions