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
with
Underscore.js
library:No standard method available. You need to iterate and you can create a simple helper:
One word of caution: Even if the above works, its generally a bad idea to extend any host or native object's
.prototype
. I did it here because it fits the issue very well. Anyway, you should probably use this function outside the.prototype
and pass the object into it instead.Or, easier yet - create a new object with the keys and values in the order you want then do look up against that object. We have had conflicts using the prototype codes above. You don't have to use the String function around the key, that is optional.
This is a small extension to the Underscorejs method, and uses Lodash instead:
FindKey will search and return the first key which matches the value.
If you want the last match instead, use FindLastKey instead.
I typically recommend lodash rather than underscore.
If you have it, use it.
If you don't, then you should consider using the lodash.invert npm package, which is pretty tiny.
Here's how you can test it using gulp:
1) Create a file called gulpfile.js with the following contents:
2) Install the lodash.invert package and gulp
3) Test that it works:
References
https://www.npmjs.com/package/lodash.invert
https://lodash.com/
Differences between lodash and underscore
https://github.com/gulpjs/gulp
Really straightforward.