looping through array of associative arrays

B

Bosconian

I'm trying to output the contents of an array of associative arrays in
JavaScript. I'm looking for an equivalent of foreach in PHP.

Example:


var games = new Array();

var teams = new Array();
teams["team1"] = "Lakers";
teams["score1"] = "78";
teams["team1"] = "Sacramento";
teams["score2"] = "88";

games[0] = teams;

var teams = new Array();
teams["team1"] = "Houston";
teams["score1"] = "94";
teams["team1"] = "Dallas";
teams["score2"] = "84";

games[1] = teams;


Desired output:

Lakers
78
Sacramento
88
Houston
94
Dallas
84

I tried (unsuccessfully):


document.open();
for (theGame in games) {
for (i in theGame) {
document.writeln(i + " = " + theGame + "<br>");
}
}
document.close();


Thanks in advance.
 
O

One Dumm Hikk

I'm trying to output the contents of an array of associative arrays in
JavaScript. I'm looking for an equivalent of foreach in PHP.

Example:

var games = new Array();

var teams = new Array();
teams["team1"] = "Lakers";
teams["score1"] = "78";
teams["team1"] = "Sacramento";
teams["score2"] = "88";

games[0] = teams;

alert(games[0]);

And you will see that games[0] isn't a copy of the array teams. You
also have a typo in your array elements, you have team1 twice and no
team2.
var teams = new Array();
teams["team1"] = "Houston";
teams["score1"] = "94";
teams["team1"] = "Dallas";
teams["score2"] = "84";

games[1] = teams;

Desired output:

Lakers
78
Sacramento
88
Houston
94
Dallas
84

I tried (unsuccessfully):

document.open();
for (theGame in games) {
for (i in theGame) {
document.writeln(i + " = " + theGame + "<br>");}
}document.close();

Thanks in advance.


Redefine your output something like this:

var games = new Array();

games[0] = ["Lakers","78","Sacramento","88"]
games[1] = ["Houston","94","Dallas","84"];

for (i in games) {
for (j in games){
document.write(games[j] + " ")
}
document.write('<br>')
}

Outputs:

Lakers 78 Sacramento 88
Houston 94 Dallas 84

There are no "Associative Arrays" in Javascript though, only arrays
with non-numeric indexes that resemble Associative Arrays in PHP.
 
L

Lee

Bosconian said:
I'm trying to output the contents of an array of associative arrays in
JavaScript. I'm looking for an equivalent of foreach in PHP.

Example:


var games = new Array();

var teams = new Array();
teams["team1"] = "Lakers";
teams["score1"] = "78";
teams["team1"] = "Sacramento";
teams["score2"] = "88";

games[0] = teams;

var teams = new Array();
teams["team1"] = "Houston";
teams["score1"] = "94";
teams["team1"] = "Dallas";
teams["score2"] = "84";

games[1] = teams;


Desired output:

Lakers
78
Sacramento
88
Houston
94
Dallas
84

I tried (unsuccessfully):


document.open();
for (theGame in games) {
for (i in theGame) {
document.writeln(i + " = " + theGame + "<br>");
}
}
document.close();



"Associative arrays" in Javascript are actually just Objects
in which the field names are used as keys.


<html>
<body>
<script type="text/javascript">

var TEAM1=0;
var TEAM2=1;
var games = [
[
{ team:"Lakers", score:78 },
{ team:"Sacramento", score:88 }
],
[
{ team:"Houston", score:94 },
{ team:"Dallas", score:84 }
]
];


for (g=0;g<games.length;g++) {
document.write(games[g][TEAM1]["team"]+"<br>"+games[g][TEAM1]["score"]+"<br>");
document.write(games[g][TEAM2]["team"]+"<br>"+games[g][TEAM2]["score"]+"<br>");
}
</script>
</body>
</html>


--
 
B

Bosconian

One Dumm Hikk said:
I'm trying to output the contents of an array of associative arrays in
JavaScript. I'm looking for an equivalent of foreach in PHP.

Example:

var games = new Array();

var teams = new Array();
teams["team1"] = "Lakers";
teams["score1"] = "78";
teams["team1"] = "Sacramento";
teams["score2"] = "88";

games[0] = teams;

alert(games[0]);

And you will see that games[0] isn't a copy of the array teams. You
also have a typo in your array elements, you have team1 twice and no
team2.
var teams = new Array();
teams["team1"] = "Houston";
teams["score1"] = "94";
teams["team1"] = "Dallas";
teams["score2"] = "84";

games[1] = teams;

Desired output:

Lakers
78
Sacramento
88
Houston
94
Dallas
84

I tried (unsuccessfully):

document.open();
for (theGame in games) {
for (i in theGame) {
document.writeln(i + " = " + theGame + "<br>");}
}document.close();

Thanks in advance.


Redefine your output something like this:

var games = new Array();

games[0] = ["Lakers","78","Sacramento","88"]
games[1] = ["Houston","94","Dallas","84"];

for (i in games) {
for (j in games){
document.write(games[j] + " ")
}
document.write('<br>')
}

Outputs:

Lakers 78 Sacramento 88
Houston 94 Dallas 84

There are no "Associative Arrays" in Javascript though, only arrays
with non-numeric indexes that resemble Associative Arrays in PHP.


Hi Randy,

Thanks for your reply.

I need the ability to reference a key by name instead of by numeric index,
where matches["team1"] equals "Houston".

Your example was instructive though and helped me achieve the desired
behavior.

BTW, I understand by definition there's no associative arrays in JavaScript,
but for my purposes the aforementioned structure suits my needs.
 
Y

Yanick

Lee said:
Bosconian said:
I'm trying to output the contents of an array of associative arrays in
JavaScript. I'm looking for an equivalent of foreach in PHP.

Example:


var games = new Array();

var teams = new Array();
teams["team1"] = "Lakers";
teams["score1"] = "78";
teams["team1"] = "Sacramento";
teams["score2"] = "88";

games[0] = teams;

var teams = new Array();
teams["team1"] = "Houston";
teams["score1"] = "94";
teams["team1"] = "Dallas";
teams["score2"] = "84";

games[1] = teams;


Desired output:

Lakers
78
Sacramento
88
Houston
94
Dallas
84

I tried (unsuccessfully):


document.open();
for (theGame in games) {
for (i in theGame) {
document.writeln(i + " = " + theGame + "<br>");
}
}
document.close();



You are on a good path, however, since both theGame and teams are
arrays and not object, those function loops through the properties and
functions of the array object, and not the indexes. In fact, the second
loop will most likely fail at the first iteration...
"Associative arrays" in Javascript are actually just Objects
in which the field names are used as keys.


<html>
<body>
<script type="text/javascript">

var TEAM1=0;
var TEAM2=1;
var games = [
[
{ team:"Lakers", score:78 },
{ team:"Sacramento", score:88 }
],
[
{ team:"Houston", score:94 },
{ team:"Dallas", score:84 }
]
];


for (g=0;g<games.length;g++) {
document.write(games[g][TEAM1]["team"]+"<br>"+games[g][TEAM1]["score"]+"<br>");
document.write(games[g][TEAM2]["team"]+"<br>"+games[g][TEAM2]["score"]+"<br>");
}
</script>
</body>
</html>

You should understand that

var myArray = new Array(); is technically the same as : var myArray =
[];
var myObject = new Object(); is technically the same as : var myObject
= {};

When dealing with myArray, you should always use for (var i=0;
i<myArray.length; i++)
When dealing with myObject, you might want to use for (var obj in
myObject)

This is a little example on how you can determine what a variable is
made of :

var a = "test";

var str = a + ' (' + (typeof a) + ') = \n';
for (var b in a) str += 'a['+b+'] = ' + a + '; ';
alert( str );

(Huge variables/objects will be hard to watch, but it can give you an
idea on how to inspect a variable.)

Of course, myObject[1] = 'foo'; and myArray[1] = 'foo'; works since
Javascript is a loose-typed language, but myObject should not have
numerical indexes.

Good luck !


BTW : when using the <script> tag, do not use type="javascript" as this
attribute was only used once upon a time when not all browsers
supported Javascript. Rather use <script type="text/javascript"> as it
is the standards today. (just like <style type="text/css">)
 
Y

Yanick

Sorry, I forgot one word in my first paragraph that leads in error :

You are on a good path, however, since both theGame and teams are
arrays and not object, those function loops through the properties and
functions of the array object, and not [only] the indexes. In fact, the
second
loop [could] most likely fail at the first iteration...
 
R

runsun pan

To my understanding, everything in javascript is an object, so an array
has the properties of an object too. That means, you can do this:

var myArray =[1,2,3]
myArray.age = 5
alert( myArray["age"] ) // --> 5
alert( myArray.age ) // --> 5

This is to make use of the "object properties" of an array.

But an array is not designed for that kind of usage. In arrays there's
a special indexing system other than the object's "key-value
association" part. When we declare myArray, [1,2,3], this special
indexing system is used such that we can do these:

alert( myArray[0] ) // --> 1
alert( myArray[1] ) // --> 2
alert( myArray[2] ) // --> 3

This is to make use of the "array properties" of an array.

To distinguish these, Yanick's point is the critical part:
When dealing with myArray, you should always use for (var i=0;
i<myArray.length; i++)
When dealing with myObject, you might want to use for (var obj in
myObject)

That is, for an array,

(a) "for (var k in myArray)" --> loop through the "object properties"
AND "array items"
(b) "for (var i=0; i<myArray.length; i++)" --> loop through "array
properties".

(b) is the correct enumerating method for an array, which will go
through items 1,2,3 of myArray. (a) will loop through 1,2,3 and "age".

So, IMHO, try not to things like this:

var teams = new Array();
teams["team1"] = "Lakers";

that "mixes the object behavior and array behavior together". If you
really need the behavior of associated array, simply use an object: var
x = {}

Btw, when using for loop, as Lee showed:

for (g=0;g<games.length;g++)

it would be a better practice to add a "var" to limit g as a variable
local to this for loop:

for (var g=0;g<games.length;g++)

otherwise if g is declared somewhere else, its value will be modified
by this for loop.
 
E

Evertjan.

runsun pan wrote on 15 okt 2006 in comp.lang.javascript:
Btw, when using for loop, as Lee showed:

for (g=0;g<games.length;g++)

it would be a better practice to add a "var" to limit g as a variable
local to this for loop:

for (var g=0;g<games.length;g++)

otherwise if g is declared somewhere else, its value will be modified
by this for loop.

This will only help you,
if the code is executed in a seperate function,
as a for() loop is not a seperate scope.

=======
var g = 14;
for ( g = 0; g < 4; g++)
a = 1;
alert(g); // 4
=======
var g = 14;
for (var g = 0; g < 4; g++)
a = 1;
alert(g); // 4
=======
 
R

runsun pan

Evertjan. said:
runsun pan wrote on 15 okt 2006 in comp.lang.javascript:


This will only help you,
if the code is executed in a seperate function,
as a for() loop is not a seperate scope.

That's true. Thx.
 
B

Bosconian

Yanick said:
Lee said:
Bosconian said:
I'm trying to output the contents of an array of associative arrays in
JavaScript. I'm looking for an equivalent of foreach in PHP.

Example:


var games = new Array();

var teams = new Array();
teams["team1"] = "Lakers";
teams["score1"] = "78";
teams["team1"] = "Sacramento";
teams["score2"] = "88";

games[0] = teams;

var teams = new Array();
teams["team1"] = "Houston";
teams["score1"] = "94";
teams["team1"] = "Dallas";
teams["score2"] = "84";

games[1] = teams;


Desired output:

Lakers
78
Sacramento
88
Houston
94
Dallas
84

I tried (unsuccessfully):


document.open();
for (theGame in games) {
for (i in theGame) {
document.writeln(i + " = " + theGame + "<br>");
}
}
document.close();



You are on a good path, however, since both theGame and teams are
arrays and not object, those function loops through the properties and
functions of the array object, and not the indexes. In fact, the second
loop will most likely fail at the first iteration...
"Associative arrays" in Javascript are actually just Objects
in which the field names are used as keys.


<html>
<body>
<script type="text/javascript">

var TEAM1=0;
var TEAM2=1;
var games = [
[
{ team:"Lakers", score:78 },
{ team:"Sacramento", score:88 }
],
[
{ team:"Houston", score:94 },
{ team:"Dallas", score:84 }
]
];


for (g=0;g<games.length;g++) {
document.write(games[g][TEAM1]["team"]+"<br>"+games[g][TEAM1]["score"]+"<br>");
document.write(games[g][TEAM2]["team"]+"<br>"+games[g][TEAM2]["score"]+"<br>");
}
</script>
</body>
</html>

You should understand that

var myArray = new Array(); is technically the same as : var myArray =
[];
var myObject = new Object(); is technically the same as : var myObject
= {};

When dealing with myArray, you should always use for (var i=0;
i<myArray.length; i++)
When dealing with myObject, you might want to use for (var obj in
myObject)

This is a little example on how you can determine what a variable is
made of :

var a = "test";

var str = a + ' (' + (typeof a) + ') = \n';
for (var b in a) str += 'a['+b+'] = ' + a + '; ';
alert( str );

(Huge variables/objects will be hard to watch, but it can give you an
idea on how to inspect a variable.)

Of course, myObject[1] = 'foo'; and myArray[1] = 'foo'; works since
Javascript is a loose-typed language, but myObject should not have
numerical indexes.

Good luck !


BTW : when using the <script> tag, do not use type="javascript" as this
attribute was only used once upon a time when not all browsers
supported Javascript. Rather use <script type="text/javascript"> as it
is the standards today. (just like <style type="text/css">)


Wow, lots of great information and syntax examples--thanks!

You're right, JavaScript is very forgiving when it comes to variable types.

In my case the use of objects is the way to go because, as you said, they're
not intended for use with numerical indexes.
 
B

Bosconian

Bosconian said:
Yanick said:
Lee said:
Bosconian said:

I'm trying to output the contents of an array of associative arrays in
JavaScript. I'm looking for an equivalent of foreach in PHP.

Example:


var games = new Array();

var teams = new Array();
teams["team1"] = "Lakers";
teams["score1"] = "78";
teams["team1"] = "Sacramento";
teams["score2"] = "88";

games[0] = teams;

var teams = new Array();
teams["team1"] = "Houston";
teams["score1"] = "94";
teams["team1"] = "Dallas";
teams["score2"] = "84";

games[1] = teams;


Desired output:

Lakers
78
Sacramento
88
Houston
94
Dallas
84

I tried (unsuccessfully):


document.open();
for (theGame in games) {
for (i in theGame) {
document.writeln(i + " = " + theGame + "<br>");
}
}
document.close();


You are on a good path, however, since both theGame and teams are
arrays and not object, those function loops through the properties and
functions of the array object, and not the indexes. In fact, the second
loop will most likely fail at the first iteration...
"Associative arrays" in Javascript are actually just Objects
in which the field names are used as keys.


<html>
<body>
<script type="text/javascript">

var TEAM1=0;
var TEAM2=1;
var games = [
[
{ team:"Lakers", score:78 },
{ team:"Sacramento", score:88 }
],
[
{ team:"Houston", score:94 },
{ team:"Dallas", score:84 }
]
];


for (g=0;g<games.length;g++) {
document.write(games[g][TEAM1]["team"]+"<br>"+games[g][TEAM1]["score"]+"<br>");
document.write(games[g][TEAM2]["team"]+"<br>"+games[g][TEAM2]["score"]+"<br>");
}
</script>
</body>
</html>

You should understand that

var myArray = new Array(); is technically the same as : var myArray =
[];
var myObject = new Object(); is technically the same as : var myObject
= {};

When dealing with myArray, you should always use for (var i=0;
i<myArray.length; i++)
When dealing with myObject, you might want to use for (var obj in
myObject)

This is a little example on how you can determine what a variable is
made of :

var a = "test";

var str = a + ' (' + (typeof a) + ') = \n';
for (var b in a) str += 'a['+b+'] = ' + a + '; ';
alert( str );

(Huge variables/objects will be hard to watch, but it can give you an
idea on how to inspect a variable.)

Of course, myObject[1] = 'foo'; and myArray[1] = 'foo'; works since
Javascript is a loose-typed language, but myObject should not have
numerical indexes.

Good luck !


BTW : when using the <script> tag, do not use type="javascript" as this
attribute was only used once upon a time when not all browsers
supported Javascript. Rather use <script type="text/javascript"> as it
is the standards today. (just like <style type="text/css">)


Wow, lots of great information and syntax examples--thanks!

You're right, JavaScript is very forgiving when it comes to variable
types.

In my case the use of objects is the way to go because, as you said,
they're not intended for use with numerical indexes.

Actually, scratch that. I'm going to restructure my data and use arrays for
some of the reasons previously mentioned. Thanks again for the information.
 
B

Bosconian

Lee said:
Bosconian said:
I'm trying to output the contents of an array of associative arrays in
JavaScript. I'm looking for an equivalent of foreach in PHP.

Example:


var games = new Array();

var teams = new Array();
teams["team1"] = "Lakers";
teams["score1"] = "78";
teams["team1"] = "Sacramento";
teams["score2"] = "88";

games[0] = teams;

var teams = new Array();
teams["team1"] = "Houston";
teams["score1"] = "94";
teams["team1"] = "Dallas";
teams["score2"] = "84";

games[1] = teams;


Desired output:

Lakers
78
Sacramento
88
Houston
94
Dallas
84

I tried (unsuccessfully):


document.open();
for (theGame in games) {
for (i in theGame) {
document.writeln(i + " = " + theGame + "<br>");
}
}
document.close();



"Associative arrays" in Javascript are actually just Objects
in which the field names are used as keys.


<html>
<body>
<script type="text/javascript">

var TEAM1=0;
var TEAM2=1;
var games = [
[
{ team:"Lakers", score:78 },
{ team:"Sacramento", score:88 }
],
[
{ team:"Houston", score:94 },
{ team:"Dallas", score:84 }
]
];


for (g=0;g<games.length;g++) {
document.write(games[g][TEAM1]["team"]+"<br>"+games[g][TEAM1]["score"]+"<br>");
document.write(games[g][TEAM2]["team"]+"<br>"+games[g][TEAM2]["score"]+"<br>");
}
</script>
</body>
</html>


Thank you for this example. It was very instructive.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,233
Members
46,820
Latest member
GilbertoA5

Latest Threads

Top