My approach involves using mongodb in conjunction with ajax calls for data retrieval. However, I have encountered an issue where the properties needed to generate HTML from JavaScript objects are sometimes missing. Consider this ajax call:
$.ajax({
url: 'api/v1/mention/'+id,
type: "GET",
dataType: "json",
data : {login : "demo"},
success: function(mention) {
display_mention_text(mention.texto);
}
});
While calling mention.texto in this case, it could also be mention.picture or any other property. The app crashes when these properties are undefined.
To address this issue, I have created a method that retrieves a property from an object and returns an empty string if it is undefined. Here are some examples of calling this method (the first argument is the object, followed by the 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 get_property method, how can I access the property if it does exist? I thought about having the object and its properties stored in an array like: object
params = ["user","name"]
but I cannot access them like this:
object.["user","name"]