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
Underscore js solution
I created the bimap library (https://github.com/alethes/bimap) which implements a powerful, flexible and efficient JavaScript bidirectional map interface. It has no dependencies and is usable both on the server-side (in Node.js, you can install it with
npm install bimap
) and in the browser (by linking to lib/bimap.js).Basic operations are really simple:
Retrieval of the key-value mapping is equally fast in both directions. There are no costly object/array traversals under the hood so the average access time remains constant regardless of the size of the data.
Main function:
Object with keys and values:
Test:
The lodash way https://lodash.com/docs#findKey
Example:
Given
input={"a":"x", "b":"y", "c":"x"}
...To use the first value (e.g.
output={"x":"a","y":"b"}
):output=Object.keys(input).reduceRight(function(accum,key,i){accum[input[key]]=key;return accum;},{})
To use the last value (e.g.
output={"x":"c","y":"b"}
):output=Object.keys(input).reduce(function(accum,key,i){accum[input[key]]=key;return accum;},{})
To get an array of keys for each value (e.g.
output={"x":["c","a"],"y":["b"]}
):output=Object.keys(input).reduceRight(function(accum,key,i){accum[input[key]]=(accum[input[key]]||[]).concat(key);return accum;},{})