I stumbled upon the YQL API to query for WOEIDs for use in Twitter, but I can see the output is not always in array. The API returns an object and I'm interested in value of response.query.results
which returns the following:
I want the result to always be an array. I can solve this by checking the result using the following code:
var count = response.query.count;
if(count === 0) {
return [];
} else if(count === 1) {
var arr = [];
arr.push(response.query.results);
return arr;
} else {
return response.query.results;
}
Is there a javascript or lodash function that can simplify the above code? It seems _.forEach
and _.toArray
will treat each property as an object if provided with a single object.
You could use Array#concat
with a default array if response.query.results
is falsy.
return [].concat(response.query.results || []);
By having zero as value for response.query.results
, you could take the Nullish coalescing operator ??
instead of logical OR ||
, which repects all values without undefoned
or null
return [].concat(response.query.results ?? []);
https://lodash.com/docs/4.17.4#concat
_.concat([],response.query.results);
would also do it.
but as @Brian pointed out, we need to handle null
being equivalent to []
so you can add
_.concat([],_.isNull(response.query.results)?[]:response.query.results);
note that this is more correct because it will work for results with falsey values (like 0
and false
etc)
in general, lodash is more robust than built in javascript. this usually works in your favour. one place this can trip you up is if results
was a string (which is an array of characters)
https://github.com/lodash/lodash/blob/4.17.4/lodash.js#L6928
function concat() {
var length = arguments.length;
if (!length) {
return [];
}
var args = Array(length - 1),
array = arguments[0],
index = length;
while (index--) {
args[index - 1] = arguments[index];
}
return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With