Api returns a JSON response at an undetermined depth where some elements may or may not be included. How to check if a property is present? Some of the options include strange names like "@param" or "$". An example for this follows.
I wrote a check for something like that, but I can’t use the point syntax for the above reasons. Help modifying this is much appreciated.
function checkValue(objectPath) {
var keys = Object.isArray(objectPath) ? objectPath : objectPath.split(".");
if (keys[0] == "window") keys.shift();
try {
return keys.inject(window, function(obj, key) {return obj[key];});
} catch (e) {
return undefined;
}
}
Example for a test object:
var obj = {
member: {
'@member-age': {
value: 42
}
}};
Before I tested it with checkValue (obj.member.age), but cannot do this for obvious reasons in this example.
chris source
share