Reputation: 897
I am displaying some results from Parse on a website but currently the loop is breaking because not all the columns have values in them.
var warningCreator = object.get("creator").get("country");
There are some instances where the user has not selected their country and that results in this error.
I am wondering if there is any way to check whether the result is undefined before calling it.
For iOs I found:
if ([object objectForKey:@"keyPath"]) {
// the object has a value for key keyPath
}
Is there anything simialar for the javaScript SDK?
*Edit (Added more code for clarity):
var WarningPoints = Parse.Object.extend("Warning_Point");
var query = new Parse.Query("Warning_Point");
query.include("creator");
query.include("position");
query.find({
success: function(results) {
markerCount = 0;
if (results.length == 0) {
alert('There are Warning Points found for specified parameters.')
};
for (var i = 0; i < results.length; i++) {
var object = results[i];
var warningCreator = object.get("creator").get("country");
var warningLat = object.get("position").get("lat");
var warningLong = object.get("position").get("long");
if((object.get("position").get("address"))!=null){
warningAddress = object.get("position").get("address");
}
console.log(warningAddress);
var warningName = object.get("name");
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
The exact error in console is:
Uncaught TypeError: Cannot read property 'get' of undefined - and the line of the error is: warningCreator = object.get("creator").get("country");
Upvotes: 0
Views: 297
Reputation: 907
if(object['keyPath']!=null){
//the object has a value for key keyPath
}
Where object is the variable that contains your data retrieved from parse. You can be more accurate in your condition checking for empty values too.
In your case:
if(object.get("creator")!=null && object.get("creator").get("country")!=null){
//the fields have a value
}
else{
//Some field is null
}
You need to do a check for each .get("field") in your statement because each field can be null.
You have 2 nested .get().get() and probably the first one is returning null so it raises the exception.
Upvotes: 1
Reputation: 897
thanks for the help.
Sometimes you just need the opinion of some fresh eyes to freshen your views again.
if(object.get("creator") != null ){
if(object.get("creator").get("country") != null ){
var warningCreator = object.get("creator").get("country");
}
}
if(object.get("position") != null ){
if(object.get("position").get("lat") != null ){
var warningLat = object.get("position").get("lat");
}
}
if(object.get("position") != null ){
if(object.get("position").get("long") != null ){
var warningLong = object.get("position").get("long");
}
}
if(object.get("position") != null ){
if(object.get("position").get("address") != null ){
var warningAddress = object.get("position").get("address");
}
}
Upvotes: 1