Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way to force javascript to always return an array

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:

  • if there are no results, it returns null
  • if there is only one result, it returns an object
  • if the are multiple results, it returns an array

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.

like image 240
Brian Avatar asked May 23 '17 21:05

Brian


2 Answers

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 ?? []);
like image 196
Nina Scholz Avatar answered Sep 21 '22 23:09

Nina Scholz


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));
}
like image 25
Tom Carchrae Avatar answered Sep 21 '22 23:09

Tom Carchrae