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']);
}
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']);
}
Share
Improve this question
edited Apr 27, 2010 at 12:27
Billy
asked Apr 27, 2010 at 12:24
BillyBilly
1252 silver badges7 bronze badges
1
-
Please tell us what your code is supposed to do, it seems that you make things more plicated than they are. I don't know whether you simplified your loop, but as it is now it is totally unnecessary, an
alert('The title is ' + myArray['title'])
would be sufficient (btw associative arrays are objects in JS). – Felix Kling Commented Apr 27, 2010 at 12:32
5 Answers
Reset to default 7You 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
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>");
}
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]);
}
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]);
}
As @Nick Craver posted, loop through your data object (associative array), preferrably using the pact 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
}
}