0

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

Community
  • 1
  • 1
Rahul Dagli
  • 4,301
  • 15
  • 47
  • 85

3 Answers3

4

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");
});
Umesh Sehta
  • 10,555
  • 5
  • 39
  • 68
3

You need to use brackets notation and a string giving the full variable name. topics_page_no.topic_[topic_id] is looking up a property on topics_page_no called topic_ and then trying to look up a property on that which matches the topic_id. Instead, you want to combine "topic_" with topic_id to form the complete name of the property to look up on topics_page_no:

So:

var topic_id = $(this).data('topic-id');
console.log(topics_page_no["topic_" + topic_id][0] + ".html");
// -----------------------^^^^^^^^^^^^^^^^^^^^^
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

you can use 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");
});
Vikram
  • 710
  • 8
  • 12