artooras
artooras

Reputation: 6795

Checking if object is Array in Parse.com CloudCode

I have this code running on Parse.com CloudCode

queryContact.find().then(function(results) {

    console.log(typeof results); // object

    if (results.constructor !== Array) {

        response.success("Found zero results");

    } else {

        console.log("WHY DID IT GO THROUGH!!!");
    }

}).then...

The find() function normally returns an array, but in my test case it returns 0 results. By logging to console I managed to see that in this case results is a typeof object. I want to proceed with else case only if results is typeof Array. However, my checks fail to capture this, and the code keeps falling through into the else section. None of the checks from this SO question work for me.

Upvotes: 0

Views: 217

Answers (4)

artooras
artooras

Reputation: 6795

I ended up using

if (results.length === 0) {

Somehow this just worked for me.

Upvotes: 2

Andy
Andy

Reputation: 63524

You can use the following to return the names of JavaScript types:

function toType(x) {
  return ({}).toString.call(x).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
}

toType([]); // array
toType({}); // object

DEMO

Upvotes: 0

Amit Prajapati
Amit Prajapati

Reputation: 14315

Try this.

 if( Object.prototype.toString.call( someVar ) === '[object Array]' ) {
   alert( 'Array!' );
 }else{
   alert( 'object!' );
 }

Upvotes: 0

Fizer Khan
Fizer Khan

Reputation: 92745

To check an object is array

 Object.prototype.toString.call(results) === '[object Array]'

Upvotes: 1

Related Questions