I am going to test if 'session' property exists:
console.log(queryData)
console.log(typeof queryData)
if ('session' in queryData) {
console.log('in')
}
else {
console.log('not in')
}
if (queryData.hasOwnProperty('session')) {
console.log('has own propety')
}
Its result is:
[Object: null prototype] { session: '0geBdiCsfczLQiT47dd45kWVN2Yp' }
object
in
/home/ubuntu/22.enmsg/cli/main.js:72
if (queryData.hasOwnProperty('session')) {
^
TypeError: queryData.hasOwnProperty is not a function
Why does the hasOwnProperty NOT work?
The hasOwnProperty() method returns true if the specified property is a direct property of the object — even if the value is null or undefined . The method returns false if the property is inherited, or has not been declared at all.
The hasOwnProperty() method returns true if the property is directly present in the object (not in its prototype chain). If an object is an Array, then the hasOwnProperty() method can check if an index is available (not empty) in the array.
For inherited properties, in will return true . hasOwnProperty , as the name implies, will check if a property is owned by itself, and ignores the inherited properties.
The hasOwnProperty() method in JavaScript is used to check whether the object has the specified property as its own property. This is useful for checking if the object has inherited the property rather than being it's own.
Most objects in javascript inherit from Object; it's possible to intentionally create objects that inherit from nothing (i.e., null
), and therefore they won't have any of the typical methods you'd expect to live on the object.
You would normally know if your code was doing this, so the object might be something passed to you from another library.
A way around the error is to call hasOwnProperty
on Object explicitly, and bind it to the object, like so:
// Calls "hasOwnProperty" on queryData, even if queryData has
// no prototype:
console.log(Object.hasOwnProperty.bind(queryData)('session'));
EDIT: Just editing to add an opinion, which is that a much better line for your purposes is the simple truthy check if (queryData.session) {
. The vagueness of this check is a strength when what you're asking is "did a session get passed?" - if session is null, undefined, false, empty string, or the key is missing altogether, the answer is clearly "no".
The easiest solution is to convert your null-prototype object to a standard javascript Object. You can do so by:
OBJjavascript = JSON.parse(JSON.stringify(objNullPrototype));
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