How to get a key in a JavaScript object by its value?
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?
Solution 1:
function getKeyByValue(object, value) {
return Object.keys(object).find(key => object[key] === value);
}
ES6, no prototype mutations or external libraries.
Example,
function getKeyByValue(object, value) {
return Object.keys(object).find(key => object[key] === value);
}
const map = {"first" : "1", "second" : "2"};
console.log(getKeyByValue(map,"2"));
Solution 2:
No standard method available. You need to iterate and you can create a simple helper:
Object.prototype.getKeyByValue = function( value ) {
for( var prop in this ) {
if( this.hasOwnProperty( prop ) ) {
if( this[ prop ] === value )
return prop;
}
}
}
var test = {
key1: 42,
key2: 'foo'
};
test.getKeyByValue( 42 ); // returns 'key1'
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.
Solution 3:
As said, iteration is needed. For instance, in modern browser you could have:
var key = Object.keys(obj).filter(function(key) {return obj[key] === value})[0];
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:
const key = Object.keys(obj).find(key => obj[key] === value);
Of course it can be also a function:
const getKeyByValue = (obj, value) =>
Object.keys(obj).find(key => obj[key] === value);