Reputation: 125
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']);
}
Upvotes: 1
Views: 4649
Reputation: 310
var i;
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";
for (i = 0; i < mycars.length; i++) {
document.write(mycars[i] + "<br>");
}
Upvotes: 2
Reputation: 5075
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
}
}
Upvotes: 0
Reputation: 175866
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]);
}
Upvotes: 0
Reputation: 630549
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
Upvotes: 7
Reputation: 196132
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]);
}
Upvotes: 0