Wednesday, March 28, 2012

Javascript Hash Table

HashTable in Javascript.
Using Javascript HashTables. 
JavaScript HashTables.

Didn't write here for a while now, and I just had a question from one of the programmers in our company.

Hash tables in .Net are piece of cake.  Simply creating a dictionary or an actual hashtable object and that it.
Well, as I always say - JavaScript is an Object Oriented scripting language. Because of that - hash tables in JavaScript are a piece of cake.  With cherries on top.

So, were gonna create an array which will contain the workers data in Json format (no need to panic, this is very simple example).
The Worker object will have Id.  Unfortunately, the array has some duplications and besides - all I need is the ID and the Name.

var hashtable = new Object();
var _array = [];
_array = FillWorkersData(); // demo function which will return json data.

for (var i in _array)
     var Worker = _array[i];
     if (_hashtable.hasOwnProperty(Worker.Id))
          // hashtable already contains this worker

     _hashtable[Worker.Id] = Worker.Name;

Elad Shalom,
CTO at