Tuesday, 15 February 2011

javascript - Accessing an associative array using jQuery -



javascript - Accessing an associative array using jQuery -

i have associative array here -

var dataset = { "person" : [ {"userlabels": ["name","role"]}, {"tagnames": ["lname","role"]}, {"tableclass": "width530"}, {"colwidths": ["50%","50%"]} ] }

i tried accessing 'userlabels' object using jquery using various methods failed. think doing wrong basics. want userlabels object accessed using jquery , result should array, can perform jquery.inarray() operation.

firstly, here's how can access dataset using method 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 can utilize variables in place of specifying names i.e. var propname ='userlabels'; alert(dataset.person[0][propname]); //what follows how search if value in array 'userlabels' $.inarray('name', dataset.person[0].userlabels);

i'd inquire why you're doing in such 'interesting way'. why don't create them objects?

that's if because if think it, person object , should noted arrays objects in javascript 'length' property, though won't elaborate on here (feel free research though). i'm guessing it's because don't know how iterate on object properties. of course of study if makes more sense you, go it.

note 1 of differences between array , object object properties need defined; you'll notice gave 'name' , 'role' values of 'undefined' below.

in case, here do:

var dataset = { "person" : { "userlabels": {"name" : undefined,"role": undefined}, "tagnames": {"lname" : undefined,"role" : undefined}, "tableclass": "width530", "colwidths": ["50%","50%"] } }; (var in dataset) { //iterate on objects in dataset console.log(dataset[i]); //i prefer utilize console.log() write it's in firefox alert(dataset[i]); // works in ie. } //by using object need is: dataset.person.userlabels.hasownproperty('role'); //returns true or false

anyways, hope helps.

javascript jquery arrays associative-array

No comments:

Post a Comment