Geuis
Geuis

Reputation: 42277

When creating an object, if a value is undefined don't include in the new object

Primarily an es6/7 question dealing with object destructuring.

Suppose I have this sample function:

const sample = (var1, var2) => {
  const obj = {
   one: var1
  };

  if (var2) {
    obj.two = var2;
  }

  return obj;
};

Its a way of saying, "the first argument is expected, if the 2nd argument is defined add it to the object too".

Is there a more elegant way to achieve the same effect but with object destructuring?

Upvotes: 1

Views: 105

Answers (1)

Thomas
Thomas

Reputation: 12657

You can also write your function as

const sample = (one, two) => two? {one, two}: {one};

Its a way of saying, "the first argument is expected, if the 2nd argument is defined add it to the object too"

As with your code, be careful with the values you add as a second argument. There are way more falsy values than just undefined, some of which you may want to assign to the result. If the criteria is whether the second argument is defined, I'd explicitly check against undefined:

const sample = (one, two) => two !== undefined? {one, two}: {one};

Upvotes: 3

Related Questions