Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find value using key in javascript dictionary

I have a question about Javascript's dictionary. I have a dictionary in which key-value pairs are added dynamically like this:

var Dict = [] var addpair = function (mykey , myvalue) [   Dict.push({     key:   mykey,     value: myvalue   }); } 

I will call this function and pass it different keys and values. But now I want to retrieve my value based on the key but I am unable to do so. Can anyone tell me the correct way?

var givevalue = function (my_key) {   return Dict["'" +my_key +"'"]         // not working   return Dict["'" +my_key +"'"].value // not working } 

As my key is a variable, I can't use Dict.my_key

Thanks.

like image 660
A_user Avatar asked Jul 09 '12 10:07

A_user


People also ask

How do you find the key of an object with its value?

To get an object's key by it's value:Call the Object. keys() method to get an array of the object's keys. Use the find() method to find the key that corresponds to the value. The find method will return the first key that satisfies the condition.


1 Answers

Arrays in JavaScript don't use strings as keys. You will probably find that the value is there, but the key is an integer.

If you make Dict into an object, this will work:

var dict = {}; var addPair = function (myKey, myValue) {     dict[myKey] = myValue; }; var giveValue = function (myKey) {     return dict[myKey]; }; 

The myKey variable is already a string, so you don't need more quotes.

like image 156
Matt Gibson Avatar answered Sep 28 '22 15:09

Matt Gibson