111

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

0

3 Answers 3

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.

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

3 Comments

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.
@flyingsheep No, it only works in comprehensions. Try it: coffeescript.org/#try:own%20key%20of%20obj
ah, ok: own = (prop, obj) -> Object::hasOwnProperty.call obj, prop
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

2 Comments

This fails if the key is there but has a value of null.
In the case where one doesn't care about the key existing but being null, then obj.key? is probably the most concise.
22
obj.hasOwnProperty(name)

(to ignore inherited properties)

2 Comments

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.
This fails where the object has the value from its prototype.

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.