I have a json response as follows:
response:{
attempts: 0,
created_at: "2015-03-03 20:05:50",
created_by: null,
deleted_at: null,
display_name: null,
}
In JavaScript, i've checked it as follows:
if(data.response.display_name!=null){
return toTitleCase(data.response.display_name);
}
According to the above code, display_name
should never have passed to toTitleCase
. However, the above condition is validated as false and hence a null object is passed to the function. Looking around here, I found this: https://stackoverflow.com/a/26330848/1411975
However, trying that as
if(data.response.display_name!='null'){
return toTitleCase(data.response.display_name);
}
also gave me errors. How do I check if the value is null? I don't have control over the incoming data so there's no way I can change that to undefined.
EDITS: Any extra information I've missed out.
- The server is in Laravel if that makes a difference and the values are being picked from a MySQL db.
- The
response
object as pasted above is correct. Console.log for
data.response
attempts: 0 created_at: "2015-03-03 20:05:50" created_by: null deleted_at: null display_name: null
Console.log for
data.response.display_name
null
Error on using second method:
TypeError: Cannot read property 'replace' of null
Since
toTitleCase
has areplace()
method implemented.
EDIT[2]:
function returnUsername(data){
if(data.response.display_name !="" || data.response.display_name!=null){
return toTitleCase(data.response.display_name);
}else{
return toTitleCase(data.response.username);
}
}
function toTitleCase(str){
return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
Full trace:
TypeError: Cannot read property 'replace' of null
at toTitleCase (app.js:850)
at returnUsername (app.js:842)
at app.js:498
at angular.js:8148
at l.promise.then.J (angular.js:11659)
at l.promise.then.J (angular.js:11659)
at angular.js:11745
at h.$get.h.$eval (angular.js:12788)
at h.$get.h.$digest (angular.js:12600)
at h.$get.h.$apply (angular.js:12892)