57

Does JQuery support Dictionaries (key, value) collection ?

I would like to set the following data in a structure

[1, false]
[2, true]
[3, false]

with the ability to add, lookup, delete and update.

Any help!

Homam
  • 23,263
  • 32
  • 111
  • 187
  • What's wrong with Javascript's associative array? – kennytm Mar 23 '11 at 07:48
  • While Javascript supports a dictionary-type of collection, why not just store the values in an array since your keys are numerical? – kevmo314 Mar 23 '11 at 07:49
  • Do you need to store the data with respect to a DOM element or in general.Why cant you use a simple javascript object.If the data needs to be stored with respect to particular DOM elements you could check out http://api.jquery.com/jQuery.data/ – frictionlesspulley Mar 23 '11 at 07:50
  • Storing the required structure is possible with Javascript's `JSON`, as an array of objects (`[[1, false],[2, true],[3, false]]`) or with key, value association (`[{"id": 1, "enabled": false},{"id": 2, "enabled": true},{"id": 1, "enabled": false}]`). But I'm not sure there are in-built methods for manipulation. – Amil Waduwawara Mar 23 '11 at 07:54
  • I haven't known that I can do that with Javascript. I'm a beginner. Thanks a lot. – Homam Mar 23 '11 at 08:12
  • @AmilWaduwawara: Why use JSON for that? JSON is a string. I don't think that is what the OP wants. JavaScript objects are good enough and JS object !== JSON. – Felix Kling Mar 23 '11 at 08:13
  • @John: Reading a tutorial is never wrong: https://developer.mozilla.org/en/JavaScript/Guide – Felix Kling Mar 23 '11 at 08:14
  • @Amil Waduwawara: JSON is a text format for representing objects, and it's not part of Javascript but based on Javascript syntax. I think that you mean an *object literal*. If you use the keys as keys instead of values, there are built-in methods for manipulations, otherwise you have to loop the array to manipulate it. – Guffa Mar 23 '11 at 09:01

5 Answers5

116

No, jQuery doesn't, but Javascript does.

Just use an object:

var dict = {
  "1" : false,
  "2" : true,
  "3" : false
};

// lookup:
var second = dict["2"];
// update:
dict["2"] = false;
// add:
dict["4"] = true;
// delete:
delete dict["2"];
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • Thanks a lot. small question: Can I initialize it with no values ? – Homam Mar 23 '11 at 08:14
  • 6
    @John: Yes, just omit the values: `var dict = {};`. – Felix Kling Mar 23 '11 at 08:15
  • You should think about updating the answer to include `map` - would be really helpful for the future. (even though such answers shouldn't become the single point of truth, aka a manual) –  Mar 06 '16 at 21:00
  • 1
    This is not `hasOwnProperty` safe. – Peter Mar 08 '16 at 22:33
  • @AndreasNiedermair: What do you mean by map? – Guffa Mar 08 '16 at 22:42
  • @Peter: What do you mean by "hasOwnProperty safe"? – Guffa Mar 08 '16 at 22:44
  • If someone were to look for a key named `hasOwnProperty` it would return `Object.prototype.hasOwnProperty`. Furthermore, if this property was overwritten, then code invoking `dict.hasOwnProperty()` would fail. – Peter Mar 08 '16 at 22:48
  • 1
    @Guffa, basically this is a flaw with JavaScript. The only way around this is to wrap the object and with safe dictionary API to get and set key/values. `map` is an ES6 solution. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map – Peter Mar 08 '16 at 23:03
  • What would be the syntax for adding a new entry in `dict` for an already existing key? Considering I want to add `"2" : "false"` to `var dict = { "1" : false, "2" : true, "3" : false };` – user1928158 Jul 08 '16 at 09:02
  • 1
    @user1928158: It's not possible to have duplicate keys in an object. They key `"2"` can only have a single value, so setting it will overwrite the previous value. If you need multiple values for keys then consider using arrays as values, i.e. `{ "1" : [ false ], "2": [ true, false ], "3" : [ false ] }`. That of course involves more code for using and manipulating the object. Another alternative would be to use an array of objects, e.g. `[ { key: "1", value: false }, { key: "2", value: true }, { key: "2", value: false }, { key: "3", value: false }, ]`. – Guffa Jul 12 '16 at 09:54
  • how to recuparate `myDict.Keys`? – serge Jan 15 '19 at 15:33
6

jQuery, no. But JavaScript does. There are only two structures in JavaScript, arrays and objects.

Objects can be used as dictionary, where the properties are the "keys":

var dict = {
    1: true,
    2: true,
    3: false
};

Properties of objects can be either accessed with dot notation, obj.property (if the property name is a valid identifier, which a digit as used above is not) or with array access notation, obj['property'].

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • don't you think since `console.log(dict.1)` is impossible to write it is very confusing, espacially on cases like: `var foo = {3: true, 2: true, 1: false}; console.log(foo[1]);` – Caspar Kleijne Mar 23 '11 at 08:14
  • @CasparKleijne: Not really sure *what* you think is confusing. You mean it could be confused with an array? Imo one should always know which data structure one is dealing with. – Felix Kling Mar 23 '11 at 08:19
  • What would be the syntax for adding a new entry in `dict` for an already existing key? Considering I want to add `"2" : "false"` to `var dict = { "1" : false, "2" : true, "3" : false };` – user1928158 Jul 08 '16 at 09:05
3

You don't need separate dictionary classes, since Javascript objects act as dictionaries. See this:

var userObject = {}; // equivalent to new Object()
userObject["lastLoginTime"] = new Date();
alert(userObject["lastLoginTime"]);

Full article here: http://msdn.microsoft.com/en-us/magazine/cc163419.aspx

Geo
  • 93,257
  • 117
  • 344
  • 520
3

With pure JavaScript,

var myDictionary = new Object();
myDictionary[1] = false;
myDictionary[2] = true;
myDictionary[3] = false;

function look(i) { return myDictionary[i];}
look(1); // will return false
Mithun Sreedharan
  • 49,883
  • 70
  • 181
  • 236
2

Yes, you can use object to do this:

var myDict = { 1:false , 2:true , 3:false };
Benoît
  • 7,395
  • 2
  • 25
  • 30
  • What would be the syntax for adding a new entry in `dict` for an already existing key? Considering I want to add `"2" : "false"` to `var dict = { "1" : false, "2" : true, "3" : false };` – user1928158 Jul 08 '16 at 09:04