Rahul Dagli Rahul Dagli - 6 months ago 13
Javascript Question

How to access object properties using variable containing underscore

I'm trying to access object properties using variable containing underscore however, its giving error

Uncaught ReferenceError: topic_ is not defined
. I did look into this question for solution Dynamically access object property using variable however it didn't work.

var topics_page_no = {
topic_1: [2,3,4],
topic_2: [5,6,7]
}

/* Navigate to particular topic's first page based on selection */
$(document).on('click', '.topic-menu-dropdown-item', function(){
var topic_id = $(this).data('topic-id');
console.log(topics_page_no.topic_[topic_id][0] + ".html");
});


Expected output:
2.html / 5.html

MKA MKA
Answer

you can try Bracket notation like this:

 /* Navigate to particular topic's first page based on selection */
$(document).on('click', '.topic-menu-dropdown-item', function () {
    var topic_id = $(this).data('topic-id');
    console.log(topics_page_no["topic_" + [topic_id]][0] + ".html");
});
Comments