javascript-kit icon indicating copy to clipboard operation
javascript-kit copied to clipboard

Use Array.isArray to check if query is an array

Open edance opened this issue 7 years ago • 3 comments

Running this in node, I was hitting an error. I was getting typeof Object instead of array.

This fix is only supported in IE 9 and above (not sure if you all are supporting IE 8).

If IE 8 is required, we can switch this to:

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

edance avatar Apr 30 '17 19:04 edance

Hi @edance, what's your version of node and how did you have your error? Any call to the query function throw an error because of this?

arnaudlewis avatar May 04 '17 10:05 arnaudlewis

Hi @arnaudlewis,

I am using node v6.10.0 and prismic 3.5.6.

My code looks like this:

const query = [
  Prismic.Predicates.at('document.type', documentType),
  Prismic.Predicates.fulltext('document', params.q || ''),
];

return Prismic.api(URL).then((api) => {
  return api.query(query, {
    page: params.page || 1,
    pageSize: params.pageSize || 20,
    orderings: `[my.${documentType}.date desc]`,
  });
});

In this check:

query.constructor === Array && query.length > 0 && query[0].constructor === Array

I pass everything except for the last conditional. For me:

query[0].constructor === object

But switching to isArray fixed the issue.

edance avatar May 04 '17 12:05 edance

Also another thought...

Technically we need to check if all the objects in the array are arrays, not just the first one. We could do something like this to check that the object is an array of arrays.

Array.isArray(query) && query.every((x) => Array.isArray(x))

edance avatar May 04 '17 15:05 edance