-2

is there any easy way to get the key from the key/value object, if I know the value?

For example I know that value is "red" in these data:

1: 'red',
2: 'blue',
3: 'yellow'

And I want to be able to track number 1 with that. I am looking for the solution without the loops over an object, to be more exact, I would like to know if there is something like the vice-versa solution like this:

var nameOfColor = colors[1];

Or is there no such way? Thanks a lot guys!

Tomáš Mocek
  • 398
  • 3
  • 14
  • Why don't you use `array` ? – Hearner Aug 12 '15 at 14:13
  • For any object: http://stackoverflow.com/questions/9907419/javascript-object-get-key-by-value For an array: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf – Domino Aug 12 '15 at 14:15

1 Answers1

0

You can do the following, by using Object.keys() method and .filter() method.

  var obj = {
    1: 'red',
    2: 'blue'
  }

  Object.prototype.getKey = function(value) {
    var self = this;
    //Retrieve all key of current object
    return Object.keys(self).filter(function(elm){
      //Then, if current object get current key
      return self.hasOwnProperty(elm)
      //true if value are equals
      ? self[elm] === value
      //Otherwise false
      : false;
    });
  }

  console.log(obj.getKey('red'));
Paul Boutes
  • 3,285
  • 2
  • 19
  • 22