2017-07-06 78 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')