Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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<string, int> statistics;  statistics["Foo"] = 10; statistics["Goo"] = statistics["Goo"] + 1; statistics.Add("Zoo", 1); 

Is there an Hashtable or something like Dictionary<TKey, TValue> in JavaScript?
How could I store values in such a way?

like image 714
George2 Avatar asked Jul 30 '09 17:07

George2


People also ask

Are there hash tables in JavaScript?

There exist two components of Hash tables in JavaScript: an “Object” and a “Hash Function”: Object: An object contains the hash table in which the data is stored.

Is there a hash function in JavaScript?

Definition of JavaScript hash() Hash function in Javascript is any function that takes input as arbitrary size data and produces output as fixed-size data. Normally, the returned value of the hash function is called hash code, hash, or hash value.

Is a JavaScript Object A hash table?

A JavaScript Object is an example of a Hash Table because data is represented a key/value pairs. A hashing function can be used to map the key to an index by taking an input of any size and returning a hash code identifier of a fixed size.

What is key-value pair in JavaScript?

An object contains properties, or key-value pairs. The desk object above has four properties. Each property has a name, which is also called a key, and a corresponding value. For instance, the key height has the value "4 feet" . Together, the key and value make up a single property.


1 Answers

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 */ } 
like image 121
Alek Davis Avatar answered Oct 31 '22 21:10

Alek Davis