111

In CoffeeScript, what is the simplest way to check if a key exists in an object?

ajsie
  • 77,632
  • 106
  • 276
  • 381

3 Answers3

186
key of obj

This compiles to JavaScript's key in obj. (CoffeeScript uses of when referring to keys, and in when referring to array values: val in arr will test whether val is in arr.)

thejh's answer is correct if you want to ignore the object's prototype. Jimmy's answer is correct if you want to ignore keys with a null or undefined value.

Trevor Burnham
  • 76,828
  • 33
  • 160
  • 196
  • 2
    most likely `own key of obj` works, too, to aditionally test `.hasOwnProperty()`. the “most likely” comes from me not having tried, but this syntax working in comprehensions. – flying sheep Jan 13 '13 at 21:15
  • 2
    @flyingsheep No, it only works in comprehensions. Try it: http://coffeescript.org/#try:own%20key%20of%20obj – Trevor Burnham Jan 13 '13 at 22:24
  • ah, [ok](https://github.com/jashkenas/coffee-script/issues/1019): `own = (prop, obj) -> Object::hasOwnProperty.call obj, prop` – flying sheep Jan 14 '13 at 13:33
38

The '?' operator checks for existence:

if obj?
    # object is not undefined or null

if obj.key?
    # obj.key is not undefined or null

# call function if it exists
obj.funcKey?()

# chain existence checks, returns undefined if failure at any level
grandChildVal = obj.key?.childKey?.grandChildKey

# chain existence checks with function, returns undefined if failure at any level
grandChildVal = obj.key?.childKey?().grandChildKey
limscoder
  • 3,037
  • 2
  • 23
  • 37
22
obj.hasOwnProperty(name)

(to ignore inherited properties)

thejh
  • 44,854
  • 16
  • 96
  • 107
  • I like this response because `key of obj` will throw an error if the value is a string or number. `Cannot use 'in' operator to search`. In this case if the object is not undefined and not null it will work. – jqualls Jun 25 '14 at 20:14
  • This fails where the object has the value from its prototype. – Brian M. Hunt Feb 28 '17 at 15:17