函数返回给定值的对象的键

时间:2013-02-11 04:38:41

标签: coffeescript

如果给出如下对象:

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

我正在寻找一个函数,如果给出值,它将返回键。我尝试了以下

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

使用此方法,提醒time.getKeyByVal(“< 1.5小时”)将实际返回8,但它会产生错误,导致脚本的其余部分被终止;

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' 

有没有更好的方法来获取给定值的密钥?

1 个答案:

答案 0 :(得分:1)

试试这个:

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