0

I have an ajax call to a php function that can return a string, an array, an object, or nothing. (Yes, I know it would be ideal to normalize this so there's only one possible return type, but it's a third-party library that was chosen by our lead dev, and I can't change that.) Is there an easy way I can test to see if it exists? I've tried this:

function doSomething(data)  //data is what's returned by a previous ajax call
     if(data.unavailableItems) {
        // do something
     }
}

But it's hitting the do something even if the unavailableItems element doesn't exist in the data array that comes into the function. I know I must be missing something really obvious, but I can't for the life of me find it.

Here's an example of the data that's coming into the function; as you can see there's no element called unavailableItems:

enter image description here

EmmyS
  • 11,892
  • 48
  • 101
  • 156
  • can you give an example of "data" for each return type? I take it that `data` was parsed either by your ajax framework, or just before its passed into this function. – NickSlash May 24 '13 at 20:25
  • @NickSlash - what shows above is a screenshot of Firefox - it's the json return from the post. – EmmyS May 24 '13 at 20:27

2 Answers2

2
if(data != void(0) && data.unavailableItems != void(0)){
  //exists
}

As Norman pointed out in the comments.. you should checkout what void 0 means

Community
  • 1
  • 1
Aidanc
  • 6,921
  • 1
  • 26
  • 30
1

A good tool to use for checking if an object contains a property is obj.hasOwnProperty(prop)

if(data.hasOwnProperty("unavailableItems")){

}

Also note, that a shim is available from John Resig for obj.hasOwnProperty

function hasOwnProperty(obj, prop) {
 var proto = obj.__proto__ || obj.constructor.prototype;
 return (prop in obj) &&
    (!(prop in proto) || proto[prop] !== obj[prop]);
}

if ( Object.prototype.hasOwnProperty ) {
 var hasOwnProperty = function(obj, prop) {
    return obj.hasOwnProperty(prop);
 }
}
Travis J
  • 81,153
  • 41
  • 202
  • 273
  • @EmmyS - Re: IE8 constraint. I see. Then checking for `void 0` is probably your best bet (as Aidanc suggests) – Travis J May 24 '13 at 20:24