Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the equivalent of "has_key" in javascript?

Tags:

if dictionary.has_key('school'): 

How would you write this in javascript?

like image 611
TIMEX Avatar asked Jul 14 '11 02:07

TIMEX


People also ask

Does Python have key 3?

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.

How do you check if an object has a key in JavaScript?

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.

Has key method in Python dictionary?

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.


2 Answers

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 
like image 158
icktoofay Avatar answered Nov 08 '22 17:11

icktoofay


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) { … 
like image 36
kay Avatar answered Nov 08 '22 18:11

kay