if dictionary.has_key('school'):
How would you write this in javascript?
Python 3 - dictionary has_key() Method The method has_key() returns true if a given key is available in the dictionary, otherwise it returns a false.
There are mainly two methods to check the existence of a key in JavaScript Object. The first one is using “in operator” and the second one is using “hasOwnProperty() method”. Method 1: Using 'in' operator: The in operator returns a boolean value if the specified property is in the object.
Python | Dictionary has_key() Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only a single value as an element, Dictionary holds key: value pair. Note: has_key() method was removed in Python 3. Use the in operator instead.
hasOwnProperty
:
if(Object.prototype.hasOwnProperty.call(dictionary, key)) { // ...
You can also use the in
operator, but sometimes it gives undesirable results:
console.log('watch' in dictionary); // always true
Either with the in
operator:
if('school' in dictionary) { …
Or probably supported in more browsers: hasOwnProperty
if({}.hasOwnProperty.call(dictionary, 'school')) { …
Could be problematic in border cases: typeof
if(typeof(dictionary.school) !== 'undefined') { …
One must not use != undefined
as undefined is not a keyword:
if(dictionary.school != undefined) { …
But you can use != null
instead, which is true for null
, undefined
and absent values:
if(dictionary.school != null) { …
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With