How to do associative array/hashing in JavaScript

How to do associative array/hashing in JavaScript

I need to store some statistics using JavaScript in a way like I’d do it in C#:
Dictionary statistics;

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

Is there an Hashtable or something like Dictionary in JavaScript?
How could I store values in such a way?

Solutions/Answers:

Solution 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"] // returns 3
point.y // returns 2

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

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

Solution 2:

var associativeArray = {};
associativeArray["one"] = "First";
associativeArray["two"] = "Second";
associativeArray["three"] = "Third";

If you are coming from an object-oriented language you should check this article.

Solution 3:

Unless you have a specific reason not to, just use a normal object. Object properties in Javascript can be referenced using hashtable-style syntax:

var hashtable = {};
hashtable.foo = "bar";
hashtable['bar'] = "foo";

Both foo and bar elements can now then be referenced as:

hashtable['foo'];
hashtable['bar'];
// or
hashtable.foo;
hashtable.bar;

Of course this does mean your keys have to be strings. If they’re not strings they are converted internally to strings, so it may still work, YMMV.

Solution 4:

All modern browsers support a javascript Map object. There are a couple of reasons that make using a Map better than Object:

  • An Object has a prototype, so there are default keys in the map.
  • The keys of an Object are Strings, where they can be any value for a Map.
  • You can get the size of a Map easily while you have to keep track of size for an Object.

Example:

var myMap = new Map();

var keyObj = {},
    keyFunc = function () {},
    keyString = "a string";

myMap.set(keyString, "value associated with 'a string'");
myMap.set(keyObj, "value associated with keyObj");
myMap.set(keyFunc, "value associated with keyFunc");

myMap.size; // 3

myMap.get(keyString);    // "value associated with 'a string'"
myMap.get(keyObj);       // "value associated with keyObj"
myMap.get(keyFunc);      // "value associated with keyFunc"

If you want keys that are not referenced from other objects to be garbage collected, consider using a WeakMap instead of a Map.

Solution 5:

Since every object in JS behaves like – and is generally implemented as – a hashtable, i just go with that…

var hashSweetHashTable = {};

Solution 6:

so in C# the code looks like:

Dictionary<string,int> dictionary = new Dictionary<string,int>();
dictionary.add("sample1", 1);
dictionary.add("sample2", 2);

or

var dictionary = new Dictionary<string, int> {
    {"sample1", 1},
    {"sample2", 2}
};

in JavaScript

var dictionary = {
    "sample1": 1,
    "sample2": 2
}

C# dictionary object contains useful methods like dictionary.ContainsKey()
in JavaScript we could use the hasOwnProperty like

if (dictionary.hasOwnProperty("sample1"))
    console.log("sample1 key found and its value is"+ dictionary["sample1"]);