Associative Arrays in Javascript


The associative array (also known as hash map) is similar to the ordinary array. Instead of indexing by integers, the associative array uses string keys. It also lacks the bookkeeping abilities of the ordinary array like sort(), splice() etc. In Javascript every object has the ability to act as an associative array.

Creating an associative array and filling it with some data:

var container = {}; container["someKey"] = 3; container["someOtherKey"] = someObject; container["anotherKey"] = "Some text"; // ... or equivalently var container = { someKey: 3, someOtherKey: someObject, anotherKey: "Some text" };
Code language: JavaScript (javascript)

Accessing elements in the associative array:

var someValue = container["someKey"]; container["otherKey"] = someValue; // ... or equivalently var someValue = container.someKey; container.otherKey = someValue;
Code language: JavaScript (javascript)

Iterating through all the elements in the associative array:

for (var key in container) { // hasOwnProperty() checks that attribute is from non-inherited prototype if (container.hasOwnProperty(key)) { var element = container[key]; } }
Code language: JavaScript (javascript)

Deleting a key in the associative array:

delete container["someKey"]; // ... or equivalently delete container.someKey; // Notice: Don't assign null to the deleted key as // this will re-create the key!
Code language: JavaScript (javascript)

Checking if a key exists in the associative array:

if (container["someKey"] === undefined) { // Key does not exist } // ... or equivalently if (container.someKey === undefined) { // Key does not exist }
Code language: JavaScript (javascript)


Leave a comment

Your email address will not be published. Required fields are marked *