Simplest way to check if key exists in object using CoffeeScript

JavascriptCoffeescript

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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

Solution 3 - Javascript

obj.hasOwnProperty(name)

(to ignore inherited properties)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionajsieView Question on Stackoverflow
Solution 1 - JavascriptTrevor BurnhamView Answer on Stackoverflow
Solution 2 - JavascriptlimscoderView Answer on Stackoverflow
Solution 3 - JavascriptthejhView Answer on Stackoverflow