简体   繁体   中英

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

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

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");
// -----------------------^^^^^^^^^^^^^^^^^^^^^

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM