1

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

1 Answer 1

1

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

Comments

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.