473,473 Members | 2,222 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

looping through array of associative arrays

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[i] + "<br>");
}
}
document.close();
Thanks in advance.
Oct 14 '06 #1
11 2907
On Oct 14, 6:21 pm, "Bosconian" <nob...@nowhere.comwrote:
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[i] + "<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[i]){
document.write(games[i][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.

--
Randy

Oct 14 '06 #2
"One Dumm Hikk" <on*********@ctvea.netwrote in message
news:11**********************@i42g2000cwa.googlegr oups.com...
On Oct 14, 6:21 pm, "Bosconian" <nob...@nowhere.comwrote:
>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[i] + "<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[i]){
document.write(games[i][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.

--
Randy
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.

Oct 15 '06 #3
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[i] + "<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>
--

Oct 15 '06 #4
Lee wrote:
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[i] + "<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[b] + '; ';
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 <scripttag, 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">)

Oct 15 '06 #5
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...

Oct 15 '06 #6
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.

Oct 15 '06 #7
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
=======

--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Oct 15 '06 #8

Evertjan. wrote:
runsun pan wrote on 15 okt 2006 in comp.lang.javascript:
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.
That's true. Thx.

Oct 15 '06 #9
"Yanick" <ya***********@gmail.comwrote in message
news:11**********************@k70g2000cwa.googlegr oups.com...
Lee wrote:
>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[i] + "<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[b] + '; ';
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 <scripttag, 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.
Oct 15 '06 #10
"Bosconian" <no****@nowhere.comwrote in message
news:58******************************@comcast.com. ..
"Yanick" <ya***********@gmail.comwrote in message
news:11**********************@k70g2000cwa.googlegr oups.com...
>Lee wrote:
>>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[i] + "<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[b] + '; ';
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 <scripttag, 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.
Oct 16 '06 #11
"Lee" <RE**************@cox.netwrote in message
news:eg*********@drn.newsguy.com...
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[i] + "<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.
Oct 16 '06 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
by: Stefan Richter | last post by:
Hi, I want to create an associative Array with a PHP variable (article ID) as Key and another associative array as it's value. How do I instanciate it, how can I fill it? I want something...
2
by: paul | last post by:
Hi all, I have a 2D array, which I am trying to access, but I am having problems doing this: If, for instance, I use a nested for loop to go through the values, using something like echo...
6
by: mark4asp | last post by:
Suppose I have the following code. It functions to randomly select a city based upon the probabilities given by the key differences in the associative array. . Eg. because the key difference...
4
by: Robert | last post by:
I am curious why some people feel that Javascript doesn't have associative arrays. I got these definitions of associative arrays via goggle: Arrays in which the indices may be numbers or...
47
by: VK | last post by:
Or why I just did myArray = "Computers" but myArray.length is showing 0. What a hey? There is a new trend to treat arrays and hashes as they were some variations of the same thing. But they...
7
by: Robert Mark Bram | last post by:
Hi All! How do you get the length of an associative array? var my_cars= new Array() my_cars="Mustang"; my_cars="Station Wagon"; my_cars="SUV"; alert(my_cars.length);
104
by: Leszek | last post by:
Hi. Is it possible in javascript to operate on an array without knowing how mamy elements it has? What i want to do is sending an array to a script, and this script should add all values from...
13
by: sathyashrayan | last post by:
Dear group, pls go through the following function definition: function at_show_aux(parent, child) { var p = document.getElementById(parent); var c = document.getElementById(child); var top ...
30
by: josh | last post by:
Hi all, what does it meaning that strange sintax (look at the object :) ? if I have i.e. array.length I can use array. and is it IE/Firefox compatible??
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.