0

I'm new in JavaScript. My need is to use key-value data in it. But I didn't see the dictionary data type in JavaScript. Can somebody help me what is the best data type I should use for this purpose.

Thanks & Regards, Abhishek

Zim84
  • 3,404
  • 2
  • 35
  • 40
  • What is the a problem using a regular object in you use-case? ([How do I implement a Dictionary or Hashtable in Javascript?](http://stackoverflow.com/questions/1208222/how-do-i-implement-a-dictionary-or-hashtable-in-javascript)) – t.niese Feb 28 '16 at 18:23

5 Answers5

2

just use an object:

var obj = {};
obj["a"]=5;
console.log(obj["a"]); // 5
Or Yaniv
  • 571
  • 4
  • 11
2

In Javascript you can imagine every object as a key-value object.

For your purpose just use the following code:

var myDict = {};
myDict.object1 = 42;

You can also use numbers and strings as keys:

var key = "message";
myDict[key] = "hello";
alert(myDict[key]);

var key2 = 5;
myDict[key2] = "five";

I hope that i could help you.

Luca Schimweg
  • 747
  • 5
  • 18
  • Given that OP is a beginner, it's worth noting that you don't have to use a variable to store the key; a literal works as well. Pretty much anything may be used as a key, but it all gets cast to a string, so `myDict[1]` and `myDict["1"]` are the same key. – The Busy Wizard Feb 28 '16 at 18:31
  • Yea but I wrote that you can use for example `myDict.object1 = 42`. – Luca Schimweg Feb 28 '16 at 18:50
1

The latest Javascript standard (known as "EcmaScript6") adds a new type called Map (see Mozilla Developer Network - JS API reference) which has less disadvantages than using a simple object.

Here is some code (taken from the website):

var myMap = new Map();
myMap.set("myKey", "value associated with 'a string'");
myMap.size; // 1
myMap.get("myKey");    // "value associated with 'a string'"

Note that is only supported in newer browsers (see Browser compatibility table here).

ingmak
  • 119
  • 1
  • 11
1

Thanks all for the quick reply:

I've solve it in this way:

var myCompDetail = {brand:"Dell", model:"Vostro", price:"15k"};

Thanks & Regards,

Abhishek Kumar

0

You can use the Object data-type for this purpose in JavaScript.

Step-1: Declare the variable

var car = {type:"Fiat", model:"500", color:"white"};

Step-2: Use it wherever required, like below:

car.type, or car.model, or car.color

Hope it will help you.

For more info you can go here: http://www.w3schools.com/js/js_objects.asp

Thanks & Regards,

Arun Dhwaj

ArunDhwaj IIITH
  • 3,833
  • 1
  • 24
  • 14