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
I use this function:
Usage:
http://jsfiddle.net/rTazZ/2/
Since the values are unique, it should be possible to add the values as an additional set of keys. This could be done with the following shortcut.
This would permit retrieval either via the key or the value:
This does assume that there are no common elements between the keys and values.
As if this question hasn't been beaten to a pulp...
Here's one just for whatever curiosity it brings you...
If you're sure that your object will have only string values, you could really exhaust yourself to conjure up this implementation:
Maybe there's something useful to build off of here...
Hope this amuses you.
Here is my solution first:
For example, I suppose that we have an object that contains three value pairs:
We can simply write a findKey(array, value) that takes two parameters which are an object and the value of the key you are looking for. As such, this method is reusable and you do not need to manually iterate the object every time by only passing two parameters for this function.
ES6, no prototype mutations or external libraries.