Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
];
like image 245
SharpCoder Avatar asked Jul 22 '13 12:07

SharpCoder


People also ask

Can you create a dictionary in JavaScript?

No, as of now JavaScript does not include a native “Dictionary” data type. However, Objects in JavaScript are quite flexible and can be used to create key-value pairs. These objects are quite similar to dictionaries and work alike.

Is an object a dictionary in JavaScript?

In Javascript, a dictionary is the same as an object. It can be initialized using the same syntax as Python. The key can be a number, a string, or an identifier. Because the dictionary is also an object, the elements can be accessed either using array notation, e.g. b[i], or using property notation, e.g. b.i.

What are dictionaries in JavaScript?

A dictionary is a general-purpose data structure for storing a group of objects. A dictionary has a set of keys and each key has a single associated value. When presented with a key, the dictionary will return the associated value.


3 Answers

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");
like image 84
musefan Avatar answered Oct 16 '22 23:10

musefan


How about this class taken from Marijn Havereke's book Eloquent JavaScript

The fiddle

function Dictionary(values) {
    this.values = values || {};

    var forEachIn = function (object, action) {
      for (var property in object) {
        if (Object.prototype.hasOwnProperty.call(object, property))
          action(property, object[property]);
      }
    };

    Dictionary.prototype.containsKey = function(key) {
      return Object.prototype.hasOwnProperty.call(this.values, key) &&
        Object.prototype.propertyIsEnumerable.call(this.values, key);
    };

    Dictionary.prototype.forEach = function(action) {
      forEachIn(this.values, action);
    };

    Dictionary.prototype.lookup = function(key) {
      return this.values[key];
    };

    Dictionary.prototype.add = function(key, value) {
      this.values[key] = value;
    };
};

var numberDic = new Dictionary({One: 1,Two: 2, Three: 3});

//-- does key exist
console.log(numberDic.containsKey("One"));
console.log(numberDic.containsKey("One"));
console.log(numberDic.containsKey("Four"));

//-- loop through each item in the dic
numberDic.forEach(function(key, value) {
  console.log(key, "is", value);
});

//-- works with complex objects
//------------------------------------------
var complexObjectDic = new Dictionary({
    Microsoft: {
        Something: "Real Interesting",
        About: "Microsoft",
        Will: "Go",
        Here: ".",
        ProductPrices: {
            WindowsPhone: 55.88,
            Windows :{
                WinXp : 180.00,
                Win7 : 200.00,
                Win8 : 150.00
            }
        }
    },
    Apple: {
        Did: "you",
        Hear: "the",
        New: "iphone",
        Will: "be coming out soon",
    }});

//-- does key exist
console.log(complexObjectDic.containsKey("Microsoft"));
console.log(complexObjectDic.containsKey("Apple"));
console.log(complexObjectDic.containsKey("Facebook"));

//-- search the dic by key
console.log(complexObjectDic.lookup("Microsoft"));
console.log(complexObjectDic.lookup("Apple"));

//-- add item to dic
complexObjectDic.add("Instagram", {
    This: "is",
    Another: "object",
    That: "I willl be Adding"
});

//-- loop through each item in the dic
complexObjectDic.forEach(function(key, value) {
    console.log(key, value);
});
like image 21
ktabarez Avatar answered Oct 16 '22 23:10

ktabarez


var widget={};
var key='k';
widget[key]='v';
alert(widget.k);//gives you v
like image 33
Jack_of_All_Trades Avatar answered Oct 16 '22 23:10

Jack_of_All_Trades