使用jQuery访问关联数组

时间:2013-02-09 01:40:18

标签: 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()操作。

3 个答案:

答案 0 :(得分:8)

首先,您可以使用自己的方法访问数据集。

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中的数组基本上是对象,具有'length'属性,虽然我不会在这里详细说明(尽管可以自由地做一些研究)。我猜它是因为你不知道如何迭代对象属性。当然,如果它对你更有意义,那就去吧。

注意数组和对象之间的区别之一是需要定义对象属性;你会注意到我在下面给出了'undefined'的'Name'和'Role'值。

在任何情况下,我都会这样做:

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

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

答案 1 :(得分:2)

var basic = dataset.person[0].userLabels;
//          |        |     |
//          |        |     --- first element = target object
//          |        --- person property
//           ---- main-object

答案 2 :(得分:0)

var userLabels = dataset.person[0].userLabels;
if ($.inArray(yourVal, userLabels) !== -1) {
    doStuff();
}