In CoffeeScript, what is the simplest way to check if a key exists in an object?
3 Answers
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.
3 Comments
flying sheep
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.Trevor Burnham
@flyingsheep No, it only works in comprehensions. Try it: coffeescript.org/#try:own%20key%20of%20obj
flying sheep
ah, ok:
own = (prop, obj) -> Object::hasOwnProperty.call obj, propThe '?' 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
mu is too short
This fails if the key is there but has a value of
null.Andrew Mao
In the case where one doesn't care about the key existing but being null, then
obj.key? is probably the most concise.obj.hasOwnProperty(name)
(to ignore inherited properties)
2 Comments
jqualls
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.Brian M. Hunt
This fails where the object has the value from its prototype.