SharpCoder SharpCoder - 10 months ago 36
Javascript Question

Creating a .net like dictionary object in Javascript

I want to create a object in JavaScript which will store values in key, value pair and I should be able to pass some key and should be able to get its value back. In .NET world we can use dictionary class for this kind of implementation. Do we have any option in JavaScript world? I am using ExtJs 4.1, so if you know of any option in ExtJS even that would work.

I have tried something like this but I cannot get value by key.

var Widget = function(k, v) {
this.key = k;
this.value = v;

var widgets = [
new Widget(35, 312),
new Widget(52, 32)


Just use a standard javascript object:

var dictionary = {};//create new object
dictionary["key1"] = value1;//set key1
var key1 = dictionary["key1"];//get key1

NOTE: You can also get/set any "keys" you create using dot notation (i.e. dictionary.key1)

You could take that further if you wanted specific functions for it...

function Dictionary(){
   var dictionary = {};

   this.setData = function(key, val) { dictionary[key] = val; }
   this.getData = function(key) { return dictionary[key]; }

var dictionary = new Dictionary();
dictionary.setData("key1", "value1");
var key1 = dictionary.getData("key1");