JavaScript associative arrays

…are not supported!

Yeah…I know, I was also frustrated when I figured out… That being said we can easily emulate a similar behavior using JavaScript.

What is an associative array?

An associative array is a data structure that associates keys (keys being strings instead of numbers) with values. In PHP associative arrays are created implementing Hash Tables. It means that PHP associative arrays are able to use all Hash Tables methods and more.

Example of an Associative Array using PHP

$associativeArray = array();
$associativeArray['Paris'] = 'Eiffel Tower';
$associativeArray['New York'] = 'Statue of Liberty';
$associativeArray['Beijing'] = 'Great Wall';

foreach ($associativeArray as $key => $value)
{
	echo 'The best tourist attraction in ' . $key . ' is the ' . $value . '.<br />;';
}
/* The best tourist attraction in Paris is the Eiffel Tower.
The best tourist attraction in New York is the Statue of Liberty.
The best tourist attraction in Beijing is the Great Wall. */

How can I emulate associative arrays in JavaScript?

In JavaScript Arrays (and other data structures) are Objects and as any other Object we can use their properties to store data.

Properties associate keys (property name) with Objects (String, Array, Function etc.) and therefore are really close to associative arrays.

Creation of an associative array emulation.

// Create a new array to emulate the associative array behavior
var fakeAssociativeArray = new Array(); // could be any Object. Example: new String() or {}
fakeAssociativeArray['Paris'] = 'Eiffel Tower';
fakeAssociativeArray['New York'] = 'Statue of Liberty';
fakeAssociativeArray['Beijing'] = 'Great Wall';

Here we only use the object properties not methods like set() to populate our object. The following code will then return 0.

// fakeAssociativeArray contains 0 values
document.writeln('fakeAssociativeArray contains ' + fakeAssociativeArray.length + ' values');

The problem is that we have not stored anything in the array yet… thus fakeAssociativeArray[0] will be undefined.

alert(fakeAssociativeArray[0]); // undefined

Comparison with using a “normal” array.

// Create a normal array
var array = new Array();
array[0] = 'Paris';
array[1] = 'New York';
array[2] = 'Beijing';

// array contains 3 values
document.writeln('array contains ' + array.length + ' values');
alert(array[0]); // Paris!

How to print out object properties?

A simple loop would do.

// Iterate through the Object and print out parameters
for (var i in fakeAssociativeArray) {
	// hasOwnProperty check if the Object as direct properties
	// or properties inherited through prototype chaining (Object.prototype)
	if (fakeAssociativeArray.hasOwnProperty(i))
	{
		document.writeln('The best tourist attraction in ' + i + ' is the ' + fakeAssociativeArray[i] + '.<br />');
	}
};
/* The best tourist attraction in Paris is the Eiffel Tower.
The best tourist attraction in New York is the Statue of Liberty.
The best tourist attraction in Beijing is the Great Wall. */

Be careful to use hasOwnProperty method to differentiate between direct properties and properties inherited through prototype chaining (see below).

alert(fakeAssociativeArray.hasOwnProperty('Paris'));   // returns true
alert(fakeAssociativeArray.hasOwnProperty('hasOwnProperty'));   // returns false

Is there any alternative?

The only one that I know about is using Mootools Hash Class.

Mootools Hash class is really close to an associative array. It provides functions such as set(), get(), empty() or getLenght(). It is a custom Object ({}) implementation which does not account for prototypes when setting, getting, or iterating. Useful because in JavaScript, we cannot use Object.prototype. Instead, we can use Hash.prototype!

var hash = new Hash({
    'name': 'John',
    'lastName': 'Doe'
});
hash.set('name', 'Michelle'); //hash.name is now 'Michelle'
hash.getLength(); // returns 2

Sources