I have a problem with my Json, you see, I query the database to check if a Patient has any referral or not. If you have it, you must return the patient data and also the referral data. And, if, on the contrary, it does not have a referral, it will only return my patient's data. This returns it to me as a Json.
What I want to do is check if that Json has a field called, for example, nameDoctor , because if it does, it will show a different data card, which will obviously include the derivation data.
let patientData = JSON.parse(this.responseText);
if(isset(patientData.nameDoctor)){
alert('Si tiene Medico');
}else{
alert('No tiene Medico');
}
Something like that. Obviously the isset is from PHP, what I want is to translate that to JS
You can ask if an object has a specific property with the method
hasOwnProperty('propiedad')
it returnstrue
orfalse
depending on whether or not the object has the property.To validate if the field exists or if it is an empty string (ie:
nameDoctor = ""
) you can use:on the other hand if you want something more structured you can use lodash's isEmpty()
https://lodash.com/docs/4.17.15#isEmpty
this library is quite useful when working with complex Json objects
It can be used
.hasOwnProperty
as said, or the operatorin
, but each method has its own things..hasOwnProperty
it doesn't check inherited properties, which makes it generally safer, but at the same time things like the following can happentrue
:On the other hand, the operator
in
only works with object literals. If we control the definition of the object we can safely usein
, otherwise, as in the case of working with dom objects for example, or objects that we do not know what they inherit from, it is preferable.hasOwnProperty
. Example ofin
:As a curiosity, the JSON.parse method can receive a kind of callback, which is actually called "reviver", inside the "reviver" we can also check if the property exists, although it is very impractical: