0

If given an object such as:

  taste =
    0: "Hate"
    1: "Really Dislike"
    2: "Dislike"
    3: ""
    4: "Like"
    5: "Really Like"
    6: "Love"

I am looking of a function that will return the key if given the value. I tried the following

  Object::getKeyByVal = (value) ->
    for prop of this
      return prop  if this[prop] is value  if @hasOwnProperty(prop)

Using this, alert time.getKeyByVal("< 1.5 hours") will acutally return 8, but it gives an error that kills the rest of the script;

Uncaught TypeError: Object function (value) {
      var prop;
      for (prop in this) {
        if (this.hasOwnProperty(prop) ? this[prop] === value : void 0) {
          return prop;
        }
      }
    } has no method 'exec' 

Is there a better way of getting the key of a given value?

1 Answer 1

1

try this :

getKeyFromValue = (obj,value)->
  for own k,v of obj
    if v==value
      return k

o =
  a:1
  b:2
  c:3
  d:4

console.log(getKeyFromValue(o,3)) # should output c

Check out a live demo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.