George2 George2 - 5 months ago 24
Javascript Question

How do I implement a Dictionary or Hashtable in Javascript?

I want to calculate/store some statistics information using JavaScript, the equivalent code in C# is below (features I need are -- key-value pair, string/int key value pair, manipulate values by keys, etc.), any ideas how to implement the same function in JavaScript? Looks like there is no built-in Dictionary or Hashtable?

Dictionary<string, int> statistics;

statistics["Foo"] = 10;
statistics["Goo"] = statistics["Goo"] + 1;
statistics.Add("Zoo", 1);


Use JavaScript objects as associative arrays.

Associative Array: In simple words associative arrays use Strings instead of Integer numbers as index.

Create an object with

var dictionary = {};

Javascript allows you to add properties to objects by using the following syntax:

Object.yourProperty = value;

An alternate syntax for the same is:

Object["yourProperty"] = value;

If you can also create key to value object maps with the following syntax

var point = { x:3, y:2 };

point["x"] // => 3;
point.y // => 2;

You can iterate through an associative array using the loop construct as follows

for(key in dict){
  var value = dict[key];
  /* use key/value for intended purpose */