I have a quite simple JavaScript object, which I use as an associative array. Is there a simple function allowing me to get the key for a value, or do I have to iterate the object and find it out manually?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Do the Java Integer and Double objects have unnece
- Keeping track of variable instances
As said, iteration is needed. For instance, in modern browser you could have:
Where
value
contains the value you're looking for. Said that, I would probably use a loop.Otherwise you could use a proper "hashmap" object - there are several implementation in JS around - or implement by your own.
UPDATE 2018
Six years passed, but I still get some vote here, so I feel like a more modern solution – for modern browser/environment – should be mentioned in the answer itself and not just in the comments:
Of course it can be also a function:
If you have (or want) a dependency on underscore.js, you can use the findKey function. Eg,
es6
es5
Keep it simple!
You don't need to filter the object through sophisticated methods or libs, Javascript has a built in function called Object.values.
Example:
This will return the object property data.
References
https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Object/values
Here's a Lodash solution to this that works for flat key => value object, rather than a nested object. The accepted answer's suggestion to use
_.findKey
works for objects with nested objects, but it doesn't work in this common circumstance.This approach inverts the object, swapping keys for values, and then finds the key by looking up the value on the new (inverted) object. If the key isn't found then
false
is returned, which I prefer overundefined
, but you could easily swap this out in the third parameter of the_.get
method ingetKey()
.Made for closure compiler to extract key name which will be unknown after compilation
More sexy version but using future
Object.entries
function