3

A api returns a JSON response at undefinable depth where some elements may or not be included. How do I check if a property is present? Some of the parameters include weird names like "@param" or "$". Example for this follows.

I wrote a check for something similar, but cannot use the dot syntax for above reasons. Help for modifiying this is highly 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 the object to test on is:

var obj = {
member: {
    '@member-age': {
        value: 42
    }
}};

Before I checked it with checkValue(obj.member.age) but cannot do this for obvious reasons in this example.

chris
  • 31
  • 3
  • Are you looking for a property *name*, or a property *value*? – Pointy Jun 16 '11 at 13:54
  • for the property name, I need to check if it is present as otherwise the output will fail. – chris Jun 16 '11 at 13:57
  • possible duplicate of [In javascript, test for property deeply nested in object graph?](http://stackoverflow.com/questions/4343028/in-javascript-test-for-property-deeply-nested-in-object-graph) and [others](http://stackoverflow.com/search?q=javascript+object+test+if+nested+property+exist) – Felix Kling Jun 16 '11 at 14:00
  • did you want the value of that property? or just wether it exists? – Patricia Jun 16 '11 at 14:02
  • @Patricia: I just need to check wether it exists. – chris Jun 16 '11 at 14:03
  • @Felix: I was not able to find a solution for the naming problem in these. My problem are those names with unknown characters. Therefore I would like to call the function like checkValue(obj['@member-age'].value); – chris Jun 16 '11 at 14:07
  • 1
    Most of the solutions there will work perfectly fine for `checkForProperty('obj.@member-age.value')`. You have to pass a string in any case. – Felix Kling Jun 16 '11 at 14:09

0 Answers0