javascript - 使用 jQuery 访问关联数组

标签 javascript jquery arrays associative-array

我这里有一个关联数组 -

var dataset = {
    "person" : [    
        {"userLabels": ["Name","Role"]},
        {"tagNames": ["lName","role"]},
        {"tableClass": "width530"},
        {"colWidths": ["50%","50%"]}
    ]
}

我尝试使用 jQuery 使用各种方法访问“userLabels”对象,但失败了。我认为我在基础知识上做错了。我希望使用 jQuery 访问 userLabels 对象,并且结果应该是一个数组,因此我可以执行 jQuery.inArray() 操作。

最佳答案

首先,以下是如何使用您拥有的方法访问数据集。

var dataset = 
{
  "person" : [  
          {"userLabels": ["Name","Role"]},
          {"tagNames": ["lName","role"]},
          {"tableClass": "width530"},
          {"colWidths": ["50%","50%"]}
         ]
};



 alert(dataset['person'][0]['userLabels']);    //style 1

 alert(dataset.person[0]['userLabels']);    //style 2

 alert(dataset.person[0].userLabels);    //style 3

 //Also you can use variables in place of specifying the names as well i.e.

 var propName ='userLabels';
 alert(dataset.person[0][propName]);

 //What follows is how to search if a value is in the array 'userLabels'
 $.inArray('Name', dataset.person[0].userLabels);

我想问你为什么要以如此“有趣的方式”来做这件事。为什么不把它们全部变成对象呢?

如果我是你,我就会这么做,因为如果你仔细想想,一个人就是一个对象,应该注意的是,数组基本上是 Javascript 中具有“长度”属性的对象,虽然我不会在这里详细说明(不过请随意做一些研究)。我猜这是因为您不知道如何迭代对象属性。当然,如果这对你来说更有意义,那就去吧。

注意数组和对象之间的区别之一是需要定义对象属性;您会注意到我在下面将“名称”和“Angular 色”值指定为“未定义”。

无论如何,我会这样做:

var dataset = 
{
  "person" : {
          "userLabels": {"Name" : undefined,"Role": undefined},
          "tagNames": {"lName" : undefined,"role" : undefined},
          "tableClass": "width530",
          "colWidths": ["50%","50%"]
        }
};

for (var i in dataset) { //iterate over all the objects in dataset
   console.log(dataset[i]);   //I prefer to use console.log() to write but it's only in firefox
   alert(dataset[i]);    // works in IE.
}

 //By using an object all you need to do is:

 dataset.person.userLabels.hasOwnProperty('Role'); //returns true or false

无论如何,希望这对您有所帮助。

关于javascript - 使用 jQuery 访问关联数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14784051/

相关文章:

ios - 使用 XCTest 检查变量是否为数组

javascript - Google Analytics 多跟踪帐户维度数据部分未显示在报告中

javascript - 如何在纯 JavaScript 中使用类似 jQuery 的选择器

javascript - Ext Js 6.2,如何在西面板触发时自动展开东面板?

javascript - 将鼠标悬停在链接上时激活覆盖背景

python - 使用 .all() 和 any() 获取搜索数组的索引

c# - 我如何为文本字段生成动态 ID 并从 asp.net 4 mvc3 中的模型数组获取数据

javascript - 没有空格的电子邮件的正则表达式

javascript - 网络上的等 Angular 柱状图

javascript - 为什么选择 JavaScript 而不是标准的浏览器虚拟机?