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 an object, or do I have to iterate the object and find it out manually? In case there is a function, which is it?
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 |
|||||||||||||||||||||
|
with Underscore.js
|
|||||||||||||||||||||
|
As said, iteration is needed. For instance, in modern browser you could have:
Where Otherwise you could use a proper "hashmap" object - there are several implementation in JS around - or implement by your own. |
|||||||||||||||||||||
|
I use this function:
Usage:
|
|||||
|
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 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. |
|||||
|
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.
|
|||
|
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. |
|||
|
|
|||
|
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. |
|||
|
var o = []; var map = {first: o, second: o}
. What wouldfind_key(o)
return? – Gareth Mar 28 '12 at 12:49