Tuesday, June 4, 2024
 Popular · Latest · Hot · Upcoming
42
rated 0 times [  49] [ 7]  / answers: 1 / hits: 21576  / 12 Years ago, sat, february 9, 2013, 12:00:00

I have an associative array here -



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


I tried accessing the 'userLabels' object using jQuery using various methods but I failed. I think I am doing something wrong with basics. I want the userLabels object to be accessed using jQuery and the result should be an array, so I can perform the jQuery.inArray() operation.


More From » jquery

 Answers
39

Firstly, here's how you can access dataset using the method you have.



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


I'd like to ask why you're doing this in a such an 'interesting way'. Why don't you just make them all objects?



That's what I would do if I were you because if you think about it, a person IS an object and it should be noted that arrays are basically objects in Javascript with a 'length' property, though I won't elaborate on it here (feel free to do some research though). I'm guessing it's because you don't know how to iterate over object properties. Of course if it makes more sense to you, go for it.



Note one of the differences between an array and an object is that object properties need to be defined; you'll notice that I gave 'Name' and 'Role' values of 'undefined' below.



In any case, here is what I would do:



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


Anyways, hope this helps.


[#80333] Thursday, February 7, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hasanb

Total Points: 321
Total Questions: 102
Total Answers: 96

Location: Burkina Faso
Member since Fri, Sep 4, 2020
4 Years ago
;