PDA

View Full Version : Associative array in JavaScript?


WA
11-12-2002, 10:40 AM
Could someone refresh my memory and confirm whether JavaScript supports associative arrays, and starting in what version of JS.

Thanks!

ionsurge
11-12-2002, 11:32 AM
I would say yes, but only if I had some idea of what you were on about... so I will not say anything.

;)


Ionsurge.

WA
11-12-2002, 11:57 AM
Well, I guess to elaborate, and the next logical question would be, what's an example syntax of associative array in JavaScript, whereby elements are defined/referenced by custom names?

joh6nn
11-12-2002, 12:14 PM
George, one word: "Objects" .

var AssocArray = new Object;

AssocArray['greeting'] = "hello";
AssocArray['farewell'] = "good bye"'
AssocArray['ultracool'] = "codingforums.com";

no length property, unfortunately.

WA
11-12-2002, 12:34 PM
Fabulous John...that makes perfect sense now that I give it some thought.

kansel
11-12-2002, 04:12 PM
According to JavaScript: The Definitive Guide (3.ed. 1998 O'Reilly)

Object is part of core JavaScript 1.0, ECMA-262 and enhanced in 1.1 (the enhancement consisted of adding the constructor property and valueOf() method)

Objects can be used as custom associative arrays as mentioned above, but don't forget about the built-in client-side associative arrays: Document.forms, Document.form[x].elements, Document.images, Document.links, Window.frames and so on.

jkd
11-12-2002, 04:50 PM
Associative array, dictionary, hash - many different names for it.

Unfortunately, Javascript doesn't support a true version of it. What it does do is have similar syntax.

Think of the [] operator as object accessors with the string argument returning the corresponding property. (Even with arrays, as you'll see).

var myObject = new Object();
myObject.myProperty = 'some value';

myObject['myProperty'] == 'some value';

The [] retrieved the myProperty value.

You can easily pretend this is a hash though.

As for arrays:

var myArray = 'hello'.split('');
myArray[0] == 'h';
myArray['0'] == 'h';

To access the "0" property, you must use the bracket notation, simply because it is in violation of syntax to go like someObject.0

This seems to imply that all arguments passed to the [] operator have their toString() method called (actually, it is probably their valueOf() method).

An experiment:


var key = new Object();
key.valueOf = function() {
return 'valueOf';
}
key.toString = function() {
return 'toString';
}

var hash = new Object();
hash[key] = 1;

alert([hash[key] == 1,
hash[key.valueOf()] == 1,
hash[key.toString()] == 1,
hash['[object Object]'] == 1
]);


Run that through, and you'll see that the toString() method is called on any argument passed to the [] operator.

beetle
11-12-2002, 05:45 PM
There's a cool notation (literal?) for defining assoc arrays....var AssocArray = {
greeting: 'hello',
farewell: 'good bye',
ultracool: 'codingforums.com'
}

jkd
11-12-2002, 09:12 PM
Originally posted by beetle
There's a cool notation (literal?) for defining assoc arrays....var AssocArray = {
greeting: 'hello',
farewell: 'good bye',
ultracool: 'codingforums.com'
}

Really an object literal (didn't I just prove that there were no such thing as hashes in JS? :D).
http://devedge.netscape.com/library/manuals/2000/javascript/1.5/guide/ident.html#1009450

beetle
11-12-2002, 09:24 PM
Originally posted by jkd
didn't I just prove that there were no such thing as hashes in JS? :DPerhaps, but I suppose I'd have to know what a hash really is before I was positive...which I don't :p

jkd
11-12-2002, 09:42 PM
Originally posted by beetle
Perhaps, but I suppose I'd have to know what a hash really is before I was positive...which I don't :p

A hash is a dictionary is an associative array. All the same thing with different names.

beetle
11-12-2002, 09:44 PM
Then what did you mean by saying...Originally posted by jkd
Unfortunately, Javascript doesn't support a true version of it.???

jkd
11-12-2002, 09:59 PM
Originally posted by beetle
Then what did you mean by saying...???

Exactly that.

The [] operator merely returns the property of the object that corresponds with the string argument.

One can debate the specifics of a hash, but exposing hash keys as object properties invites conflicts in object orientated languages.

beetle
11-13-2002, 01:48 AM
Got it. Cohesion upstairs has taken place. :D

aleceiffel1066
05-27-2009, 07:28 PM
Hi there,

This may be kind of peripheral to the original question, but here goes nothing. I have an application within which I have created a number of 'hash-like' data structures, more like collections actually:


var hshObjectCollection1 = {};
var hshObjectCollection2 = {};

where they contain multiple named objects, each of which have a series of common properties. These collections look like this:

hshObjectCollection1['named object 1'] = { namedProp1: 'value 1', namedProp2: 'value 2' };
hshObjectCollection1['named object 2'] = { namedProp1: 'value 3', namedProp2: 'value 4' };

hshObjectCollection2['named object 3'] = { namedProp3: 'value 5', namedProp4: 'value 6' };
hshObjectCollection2['named object 4'] = { namedProp3: 'value 7', namedProp4: 'value 8' };

The collected objects within each hshObjectCollection have the same number of properties, but don't necessarily have the same number of properties as the objects in another hshObjectCollection - if you know what I mean. The above code is just to setup my question. Which is:

Given the similar, but different instances of this type of collection object, is there a single generic function I can use to get any named property's value, for any object (if I know the name of the property I want and the name & **unique** value of any other property of the objects collected in that hshObjectCollection) from any of these hshObjectCollection objects?

This doesn't work:

function getHashProperty(propName, propValue, hashProperty, hashName) {
var prop = hashProperty; // e.g. 'namedProp4'
var hash = hashName; // e.g. 'hshObjectCollection2'
var key = propName; // e.g. 'namedProp3' from above
var val = propValue; // e.g. 'value 7' from above
if (key) {
for (var key in hash) {
if (hash.hasOwnProperty(key)) {
if (hash[val].key == val) {
for (prop in hash[key]) {
if (hash[key].hasOwnProperty(prop)) {
return hash[key][prop]; // should retrn 'value 8' ex above
}
}
}
}
}
}
}


Any help would be greatly appreciated. Thanks,

-alec

rnd me
05-28-2009, 12:11 AM
you might want to review javascript for-in iterations, there are several mixups in the posted code.

for example,
var hash = hashName;
should probably be
var hash = this[hashName];

which would make
if (hash[val].key == val) {
into
if (hash[key] == val) {

and others like that.
go one tiny step at a time, and figure out how the code is executing at each step.


briefly:

var ob={a:1,b:2};

for(key in ob){
alert( "key: " + key +
"\n ob[key]: "+ ob[key]
);
}


you should first understand how the above code works, and then apply the principles/syntax to your code.