首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用字符串值访问对象键

使用字符串值访问对象键
EN

Stack Overflow用户
提问于 2017-07-07 01:58:35
回答 2查看 438关注 0票数 0

我有一个手动键入的数据库,其中有一个对象,其中包含类别和每个类别的单词列表,如下所示:

代码语言:javascript
运行
复制
var words =
{
    sports: [
        'baseball', 'football', 'volleyball', 'basketball', 'soccer'],

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

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

我的HTML有一个bootstrap下拉列表,它将显示基于该列表的所有类别。我让代码将类别的值作为字符串单击:如下所示:

代码语言:javascript
运行
复制
$(document).on('click', '.dropdown-menu li a', function () {
    var selectedCategory;

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

我需要能够从该值中找到我的数据库中的键。问题是我不能访问单词。“动物”我需要去掉字符串中的引号,才能得到这样的单词列表: words.animals

我该怎么做呢?我尝试过replace(),但它不起作用。

EN

回答 2

Stack Overflow用户

发布于 2017-07-07 02:02:19

您似乎正在尝试访问与words对象中的类别相对应的值列表。键可以是字符串,所以words['animals']就是一个获取动物列表的例子。

JavaScript还允许将变量用作键,因此您可以按如下方式访问它:

代码语言:javascript
运行
复制
words[categorySelected]
票数 0
EN

Stack Overflow用户

发布于 2017-07-07 02:05:09

您可以将文本(下拉列表中的选定值)传递给函数以查找密钥

代码语言:javascript
运行
复制
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')

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44955940

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档