A simpler and more direct solution is possible:
Getting your original data:
data = {
"pendente": 0,
"cancelada": 1,
"remitida": 2
};
This expression will return the string "remitida"
:
Object.entries(data).find((key, value)=> value == 2 )[0]
Explanation:
Object.entries()
is a mixture of Object.keys()
and Object.values()
, it will remove an array of arrays based on this dictionary. The result will be the following:
[
["pendente", 0],
["cancelada", 1],
["remitida", 2]
]
Arrays has the method find()
which returns the first element whose filter function returns true
(or values equivalent to true
, nonempty strings and non-zero numbers). In this case find will return:
["remitida", 2]
Oh, yes, the "filter function" there is (key, value)=> value == 2
, an anonymous function that will receive the two items of each child array in the variables key
and value
, what they originally are. Then just test if the value
is what is expected with value == 2
.
Like I said before the find()
will return an array (IN THIS CASE), and what we want is the first item of this (which holds the key), so a [0]
after the find()
.
It would not be better to use an array and access the indexers from it?
– aviana