37

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.

1
  • 1
    FYI, capital-letter identifiers (like Dict) are normally used for class names, so using a name like Dict might confuse readers of your code. Leading-lower camelCase names (e.g. dict, myKey) would likely match up more closely with readers' expectations. Commented Dec 6, 2018 at 17:16

1 Answer 1

47

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Hi can I do reverse of it by finding key using value
Not so easily. You would need to do a loop, trying every value in the object until you got the right one, then returning that key. Problem is that there may be two values the same, so you would need to put code into addpair() to prevent duplicates.
Arrays in Javascript do use strings as keys, and anything that you try to use as an array index will be coerced to a string behind the scenes. You can confirm this by creating an object with a toString method and using it as an array index. It will use whatever the toString method returned.
@PeterOlson You're right, but I always understood that as an abuse of the array object :) It can also lead to unpredictable stuff when the Array object is prototyped as per here andrewdupont.net/2006/05/18/… added to which, things like array.length don't count the string keys, so I always stick to the integer-only line.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.