1

Can I use 'in' to check existence of non top level names in a JSON data structure in a single comparison?

I have n tier JSON data structures,

I can do: if("mbled" in jsonData), works fine

For a lower tier name:

I can do this but (works but gets clunky as I go deeper): if("pnpenvsense1" in jsonData && "light" in jsonData.pnpenvsense1)

I'd prefer something like (doesn't work, always returns false): if("pnpenvsense1.light" in jsonData)

lindsay
  • 38
  • 4
  • possible duplicate of [Check if object member exists in nested object](http://stackoverflow.com/questions/4676223/check-if-object-member-exists-in-nested-object) – Felix Kling Apr 25 '11 at 08:15

2 Answers2

1

something like:

function objExists(path, struct){
    path = path.split('.');
    for(var i=0, l=path.length; i<l; i++){
        if(!struct.hasOwnProperty(path[i])){ return false; }
        struct = struct[path[i]];
    }
    return true;
}

objExists('pnpenvsense1.light', jsonData);
  • It fails if `struct` is `0` or an empty string at one point (or any other value that evaluates to `false`). `objExists('foo', {foo: 0})` would return `false`. – Felix Kling Apr 25 '11 at 08:18
  • You should check if `struct[path[i]]` is an object when `i < path.length - 1` and if `struct[path[path.length - 1]]` is not `undefined`. Just think about what would happen if `jsonData.pnpenvsense1` is not an object but a string for instance. – Jan Apr 25 '11 at 11:35
  • @Felix - You're right, thanks, modified code. @Jan - I thought about it. Nothing would happen :P You would then check `'someString'['light']`, which would return undefined :) –  Apr 25 '11 at 16:28
  • Thanks for your suggestions, I now realise I have to write my own function – lindsay May 02 '11 at 09:32
0

try

// will check if it is defined and not false

if(pnpenvsense1.light !== undefined && pnpenvsense1.light != false ) 

  { // my code } 

http://jsfiddle.net/

arr = new Array();
arr['myKey'] = 12;
arr['myOtherKey'] =  { "first" : "yes" , "second" : false  };

if(arr.myKey !== undefined  && arr.myKey != false)
    alert("1 -> " + arr.myKey);

if(arr.myOtherKey.first !== undefined && arr.myOtherKey.first != false)
    alert("2 -> " + arr.myOtherKey.first);
DhruvPathak
  • 42,059
  • 16
  • 116
  • 175
  • I believe this will throw an exception when pnpenvsense or myOtherKey is undefined. – Jan Apr 25 '11 at 08:09