javascript-kit
javascript-kit copied to clipboard
Use Array.isArray to check if query is an array
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]'
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?
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.
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))