Miguel Moura
Miguel Moura

Reputation: 39364

Create a "Dictionary" in javascript

In C# I have a Model with 2 properties and a Dictionary with a String key:

public class Model 
{
    public string Route { get; set; }
    public string Template { get; set; }
}

Dictionary<String, Model> models;

The key is the model name and model is an instance of class model.

I need to create a similar structure in Javascript where I could Get an item from the "Dictionary" given a key or find if there is an item with a specific key in the "Dictionary".

Is something in Javascript that could replicate this?

Upvotes: 1

Views: 926

Answers (4)

Jord&#227;o
Jord&#227;o

Reputation: 56467

In Javascript, a dictionary with string keys is just a plain object:

var models = {};

Add an element:

model.myKey = 'my value';

Get an element:

var value = model.myKey;

Check that an element exists:

if (model.myKey) { ...

(note that this will yield false for any Javascript falsey value, so if you store things like 0 or '' you should use the more pedantically correct method model.hasOwnProperty('myKey'))

Remove an element:

delete model.myKey;

You can also add elements when creating the object:

var obj = {
  'an item': 1,
  anotherItem: 'another value'
};

Note that keys can be accessed with a dot notation if they're valid Javascript identifiers:

var value = obj.key;

Or as values in brackets (useful if they're not valid identifiers or if you want to use a variable):

var value = obj['A key'];

var fromVar = obj[someVariableHoldingAKeyName];

(JSHint even has a rule that checks for that)

As for your model class, it could similarly be modeled as an object with keys 'route' and 'template', e.g:

var myModel = { route: 'my route', template: 'my template' };

Upvotes: 4

Felix Kling
Felix Kling

Reputation: 816334

The next version of ECMAScript introduces Map, which allows to use a value of any data type as key. Map is already supported in a variety of browsers.

Example:

var map = new Map();
map.set('foo', data);
map.get('foo);

As already mentioned, objects are also often used as dictionaries, and sufficient in most cases. However, some care has to be taken:

  • The default prototype of objects is Object.prototype, so they already contain some "default" entries (like toString or hasOwnProperty). This can be avoided by explicitly creating an object with no prototype: var dict = Object.create(null);

  • Similar to above, because Object.prototype can be extended, your "dictionary" could be changed as well without you knowing it. Object.create(null) solves that problem as well.

Upvotes: 1

Dave Salomon
Dave Salomon

Reputation: 3297

Similar to the other answers. You're probably well off to put your model into an Array (however you're getting them), and then looping through that array to create your dictionary object.

var models = {};
var m1 = {name:'Joe',age:25};
var m2 = {name:'Bill',age:30};
var m3 = {name:'Andy',age:50};

var arr = [m1,m2,m3];
for(var m in arr){
   models[arr[m].name] = arr[m];
}

//console.log(models);
var joe = models.Joe;
var joe = models['Joe'];

Upvotes: 1

Christos
Christos

Reputation: 53958

You could create a function that would represent the random item in your dictionary:

function Model(route, template)
{
    this.route = route;
    this.template = template;
}

Then you could create an object like below:

var dictionary = { 
    "key1": new Model("route1", "template1"), 
    "key2": new Model("route2", "template2")
};

In JavaScript objects are containers for key/value pairs.

How we get the value for a specific key?

var model = dictionary["key1"];

or

var model = dictionary.key1;

If key1 isn't a key of dictionary, then you will get as model the undefined.

How we set the value for a specific key?

dictionary.key5 = new Model("route5", "template5");

What happens if there is already the key5 ?

You just assign a new value for this key. As it would happen, if we were in c#.

Above we used the constructor pattern, in order we create the values of our dictionary. This is a commonly used pattern for the creation of objects with the same properties.

Upvotes: 4

Related Questions