Monkey Raptor

Saturday, April 7, 2018

JavaScript & Python: Check if Property is in Object (or Dictionary)

JavaScript

There are more than one method to check it.

First, we can use hasOwnProperty method.

We'll expect boolean output.

Second, we can use in operator.

We'll expect boolean output.

Third, straight away access the property name we need to find out.

We'll expect the returned output to be the value of that certain property name. In this method, the returned value undefined can be ambiguous, because we can initialise a property to have an undefined value too. So, um, the first or second method above is recommended.


Python

In Python, we can use hasattr method or in operator.

Using either in operator or hasattr(dictionary, property) method, we'll expect boolean output (True / False).


Important

For checking either array/list or object/dictionary, make sure the variable instance is not undefined / null in JavaScript, or None in Python.

Therefore, we should put a preliminary test.

JavaScript

Python


Well of course, it doesn't have to be strictly like that above typing. It depends on the purpose of that particular checking.

JSLint (JavaScript linter) will surely shows warning if we use "in" for object property checking. You could use the "object property name direct access" method, or use the hasOwnProperty method. Well, because JSLint is about building good structuring habit.

JavaScript & Python: Check if Property is in Object (or Dictionary)
https://monkeyraptor.johanpaul.net/2018/04/javascript-python-check-if-property-is.html

No comments

Post a Comment

Tell me what you think...