How to get a key in a JavaScript object by its value?

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:

with Underscore.js library:

var hash = {
 foo: 1,
 bar: 2

(_.invert(hash))[1]; // => 'foo'

Solution 2:

function getKeyByValue(object, value) {
  return Object.keys(object).find(key => object[key] === value);

ES6, no prototype mutations or external libraries.


function getKeyByValue(object, value) {
  return Object.keys(object).find(key => object[key] === value);

const map = {"first" : "1", "second" : "2"};

Solution 3:

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 4:

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.


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);

Solution 5:

The lodash way

var users = {
  'barney':  { 'age': 36, 'active': true },
  'fred':    { 'age': 40, 'active': false },
  'pebbles': { 'age': 1,  'active': true }

_.findKey(users, { 'age': 1, 'active': true });
// → 'pebbles'

Solution 6:

function extractKeyValue(obj, value) {
    return Object.keys(obj)[Object.values(obj).indexOf(value)];

Made for closure compiler to extract key name which will be unknown after compilation

More sexy version but using future Object.entries function

function objectKeyByValue (obj, val) {
  return Object.entries(obj).find(i => i[1] === val);