I’m using mongodb and ajax calls to retrieve data. When it turns to javascript object, the properties that I use to generate html sometimes don’t exist.
Look at this call:
$.ajax({
url: 'api/v1/mention/'+id,
type: "GET",
dataType: "json",
data : {login : "demo"},
success: function(mention) {
display_mention_text(mention.texto);
}
});
In this case i’m calling mention.texto, but could be mention.picture or any properties. Sometimes it is undefined and crashes the app.
This method calls a property from a object and if its undefined , return an empty string.
Some examples for calling this method(the first one is an object, the other are properties):
get_property(mention,"text")
get_property(mention,"user","name")
get_property(mention,"picture")
The method is defined as follows:
function get_property(obj){
var args = Array.prototype.slice.call(arguments),
obj = args.shift();
if (checkNested(obj,args)) {
//what should I do here?
} else{
//the property is undefined and returns ""
"";
};
}
//check if a object has N levels of propertys
function checkNested(obj /*, level1, level2, ... levelN*/) {
var args = Array.prototype.slice.call(arguments),
obj = args.shift();
for (var i = 0; i < args.length; i++) {
if (!obj.hasOwnProperty(args[i])) {
return false;
}
obj = obj[args[i]];
}
return true;
}
In the first method get_property, if the property do exist, how do I call that??
I would have the object and his propertys as an array like:
object
params = ["user","name"]
but I can’t call like following:
object.["user","name"]
Replace the
ifstatement in theget_propertyfunction with theforloop from thecheckNestedfunction. Then instead of returningtrueorfalse, return the value found or"".Again, all I did was copy paste your own code from one function to the other, and change the values of the
returnstatements.