2017-07-06 94 views
0

我有一个对象,它具有类别和每个类别的单词列表,如下手类型的数据库:访问对象键

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

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

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

我的HTML有一个自举下拉式选单,将根据该列表显示所有类别。我的代码工作给我点击作为一个字符串的类别的值如下:

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

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

我需要能够找到从该值在我的数据库中的关键。 的问题是,我无法访问写着“动物” 我需要引号把我的字符串得到的话是这样的名单: words.animals

我该怎么办呢?我试过替换(),但它不起作用。

+0

我认为你正在寻找'字[categorySelected]'? – smarx

+0

使用单词['animals']或单词[var] –

回答

0

您好像正在尝试访问与words对象中的类别对应的值列表。钥匙可以是字符串,因此words['animals']将是获取动物列表的示例。

JavaScript允许变量被使用的键,这样你就可以访问它,如下所示:

words[categorySelected] 
+1

'JavaScript允许将变量用作键' - 从技术上讲,但是JavaScript的对象键*都是字符串*。所有的键都是字符串。 – Li357

+0

辉煌。有用!非常感谢解释! – lldm

+0

@AndrewLi好点!感谢您的澄清。 – rageandqq

0

您可以将文本(从下拉选择的价值下降)传递给一个函数来找到问题的关键

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')