Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get key corresponding to value in js object

I have an object such as :

var inspectionMapping = {'a_pillar_lh' : "A Pillar LH",
                       'b_pillar_lh'  : "B Pillar LH"};

console.log(inspectionMapping['a_pillar_lh']);
// Which gives me correct "A Pillar LH".

I am able to get the value corresponding to key.

But I am not able to get the key corresponding to value in javascript Object.

Such as I have "A Pillar LH" and I need to get the corresponding key which is a_pillar_lh.

I have tried to use indexOf but no success.

like image 211
RISHABH BANSAL Avatar asked Dec 11 '22 17:12

RISHABH BANSAL


1 Answers

You can simply fetch all the keys using Object.keys() and then use .find() function to get the key out from that array, and then nicely wrap it in a function to make it modular.

var inspectionMapping = {
  'a_pillar_lh': "A Pillar LH",
  'b_pillar_lh': "B Pillar LH"
};

Object.prototype.getKey = function(value) {
  var object = this;
  return Object.keys(object).find(key => object[key] === value);
};


alert(inspectionMapping.getKey("A Pillar LH"));

EDIT For those who don't want to use ES6

Object.prototype.getKey = function(value) {
      var object = this;
      for(var key in object){
         if(object[key]==value) return key;
      }
};
like image 138
void Avatar answered Dec 21 '22 21:12

void