0

In nodejs 8.10 I want a function to return a different object depending on parameters. Is there any simple way to include or not a key based on its value?

Example

// I do not like this solution, there is a 2 line body
// `c` may be undefined or a string (for example)
const f = (a, b, c) => {
  if (c) return ({ a, b, c });
  else return { a, b }
}

Can we do a simple return with c included or excluded based on its value? I expect something like this:

// I expect this kind of solution.
const f = (a, b, c) => ({ a, b, ___????___ })
Costin
  • 2,699
  • 5
  • 25
  • 43
  • 2
    You could use `arguments`. Please check [this answer](https://stackoverflow.com/questions/2141520/javascript-variable-number-of-arguments-to-function). – Paweł Sep 13 '18 at 09:10

1 Answers1

3

You have no way to do that but you can:

const f = (a, b, c) => (c ? { a, b, c } : { a, b });

or

const f = (a, b, c) => {
  const result = { a, b };
  if (c) result.c = c;
  return result;
}
np42
  • 847
  • 7
  • 13
  • First solution duplicates `a` and `b`, second one is still a 2 lines answer. This is not exactly what I am looking for. Thanks. – Costin Sep 13 '18 at 09:55