1

I am using the query-string library to parse query parameters from an URL. When the query parmater is in the form ?foo=bar, the lib returns an object like this:

{
  foo: bar
}

When in the form ?foo=bar1,bar2, the object looks like this:

{
  foo: [bar1, bar2]
}

I want to apply the function myFunction on each element of myObject.foo to obtain something like [myFunction(bar)] or [myFunction(bar1), myFunction(bar2)]

Is there a way to do it easily with something like

myObject.foo.mapOrApply(myFunction)

without having to check if this is an array ?

For now, I am forced to do it this way and I find this very unaesthetic:

Array.isArray(myObject.foo)
   ? myObject.foo.map(myFunction)
   : [myFunction(myObject.foo)];
EtienneG
  • 300
  • 5
  • 14
  • Possible duplicate of [How to detect if a variable is an array](https://stackoverflow.com/questions/1058427/how-to-detect-if-a-variable-is-an-array) – VLAZ Jul 04 '19 at 10:05

3 Answers3

7

You could use concat like this:

[].concat(myObject.foo).map(myFunction)

This works when myObject.foo is a single value or an array

Here's a snippet:

const getMapped = ({ foo }, callback) => [].concat(foo).map(callback);

 // double a single value
console.log(getMapped({ foo: 1 }, n => 2 * n))

// prefix "new" to every item in the array
console.log(getMapped({ foo: ["bar1", "bar2"] }, str => "new " + str)) 
adiga
  • 34,372
  • 9
  • 61
  • 83
2

You could convert to an array, if neccessary, then map with the function.

result = (Array.isArray(myObject.foo) ? myObject.foo : [myObject.foo]).map(myFunction);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

You can simply :

 [].concat(myObject.foo).map(myFunction)
Vinz243
  • 9,654
  • 10
  • 42
  • 86