I have the following dictionary:
diccionario = {1: "uno", 2: "dos", 3: "tres"}
I would like to see if it contains a certain key, for example the 2. How can I find out?
And by the way... I would also like to know how to check if a value is in the dictionary. How do you give it a value and get a key back?
The dictionary concept here is ambiguous:
Objects like Dictionaries (or Hash Maps)
What you call a dictionary is a basic object in Javascript.
To obtain the keys you have this functionality:
On the other hand, you could loop through the keys as follows:
But to find out if a key exists, pragmatically , you can just compare with
undefined
:Although it is true that the key can be present, but not store any value, in practice there is no difference between considering that it is not present or that its value is undefined:
If you want to know if the key really does not exist, not even with an undefined value, there is the method
hasOwnProperty
:Real dictionary (using a class designed for that purpose)
Say what you really want is a dictionary, Javascript has the Map class , which gives more possibilities than a simple object, like that the keys can be objects and not just text or numbers, or that you can ask how many elements there are:
To know that your dictionary has a specific key you can use this code:
With Object.keys(dictionary) you get all the keys of the dictionary object and with the includes function you search if there is a value "2" in the list of keys.
Well, to obtain the keys for a specific value, this would be worth it:
Hope this can help you.
Greetings.
To find out if it contains a key, you could use
.hasOwnProperty()
:To know if it contains a value, you could use the methods of
Object
:Object.values()
returns the enumerable values of the object, in the same order as they would be seen in afor in
Object.keys()
returns the enumerable keys of the object, in the same order as they would be seen in afor in
I think the best way to perform key verification is as follows:
Every object descendant of Object inherits the hasOwnProperty method. This method can be used to determine if an object has the specified property as a direct property of that object; Unlike the operator
in
, this method does not check the object's prototype chain.To get the keys:
To get the values:
To give value to a key: