0

I have a hand-typed database with an object that has categories and a list of words for each category, as below:

var words =
{
    sports: [
        'baseball', 'football', 'volleyball', 'basketball', 'soccer'],

    animals: [ 
        'dog', 'cat', 'elephant', 'crocodile', 'bird'],

    entertainment: [
        'netflix', 'movies', 'music', 'concert', 'band', 'computer']
}

My HTML has a bootstrap dropdown that will display all categories based on that list. I have the code working to give me the value of the category clicked as a string: as below:

$(document).on('click', '.dropdown-menu li a', function () {
    var selectedCategory;

    selectedCategory = $(this).text();
    //setting value of category to global variable
    categorySelected = selectedCategory;
});

I need to be able to find the key in my database from that value. The problem is that I can't access words."animals" I need to take the quotation marks off my string to get the list of words like this: words.animals

How do I do this? I've tried replace() but it doesn't work.

lldm
  • 21
  • 4

2 Answers2

1

It seems like you're trying to access the list of values corresponding to the category in your words object. Keys can be strings, so words['animals'] would be an example of getting your list of animals.

JavaScript allows variables to be used as keys as well, so you can access it as follows:

words[categorySelected]
rageandqq
  • 2,221
  • 18
  • 24
0

You can pass the text(selected value from drop down) to a function to find the key

var words = {
  sports: [
    'baseball', 'football', 'volleyball', 'basketball', 'soccer'
  ],

  animals: [
    'dog', 'cat', 'elephant', 'crocodile', 'bird'
  ],

  entertainment: [
    'netflix', 'movies', 'music', 'concert', 'band', 'computer'
  ]
}
// function to find the key
function findKey(selText) {
 //loop through the object
  for (var keys in words) {
 //get the array
    var getArray = words[keys]
  //inside each array check if the selected text is present using index of 
    if (getArray.indexOf(selText) !== -1) {
      console.log(keys)
    }

  }
}

findKey('music')
brk
  • 48,835
  • 10
  • 56
  • 78