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

2
  • 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. Commented May 24, 2013 at 20:25
  • @NickSlash - what shows above is a screenshot of Firefox - it's the json return from the post. Commented May 24, 2013 at 20:27

2 Answers 2

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

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

Sign up to request clarification or add additional context in comments.

4 Comments

You can also use data != void 0 without the parens
@TravisJ Cool! I wasn't aware that was valid. I'm not a big JS person, thanks.
For more on what the void(0) or void 0 does check out this other great SO question - stackoverflow.com/questions/1291942/…
I tried this, and it's still getting into the if statement.
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);
 }
}

1 Comment

@EmmyS - Re: IE8 constraint. I see. Then checking for void 0 is probably your best bet (as Aidanc suggests)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.