views:

79

answers:

4

Hi,

how can I get the indentifier of an associative array (not Array object) in a for loop?

like so:

var i = 0;
for(i=0;i<=myArray;i++)
{
   if(myArray.ident == 'title') alert('The title is ' + myArray['title']);
}
A: 

ident is the identifier in your case and 'title' is its value ..

Please show us the actual array ..

normally to loop through an associative array you would do it like this..

for (key in myArray)
  {
    if (key == 'title')
      alert('The title is ' + myArray[key]);
  }
Gaby
+3  A: 

You can do it using a different for() loop, like this:

var myArray = { title: "my title", description: "my description" };
var i = 0;
for(var i in myArray) {
   //if(i == 'title') is the check here...
   alert('The '+ i + ' is ' + myArray[i]);
}​

Inside the loop, i is your identifier, e.g. title and description. You can play with this example here

Nick Craver
Exactly! Thank you very much :-)
Billy
A: 

Depends somewhat on how you construct myArray, in general:

var myArray = {
   title: "foo",
   bleep: "bloop"
}

for (var k in myArray) {
   if (k == "title") 
      alert('The title is ' + myArray[k]);
}
Alex K.
A: 

As @Nick Craver posted, loop through your data object (associative array), preferrably using the compact syntax, and check whether the property matches your string:

var myData = { /* properties: values */ } ;
var string = /* string to match */ ;

    for(var n in myData) {

            if(n == string) {
                // do something
            }

    }
FK82