DEV Community

Daniel Zotti
Daniel Zotti

Posted on

#LearnedToday: Conditionally add properties to an object

👀 I noticed that many developers don’t know about this handy way to conditionally create properties for a JavaScript object.

const obj = {
  ...condition && { key: value },
};
Enter fullscreen mode Exit fullscreen mode

Example:

const res = { firstName: "Daniel", lastName: "Zotti" }

const person = {
  name: res.firstName,
  surname: res.lastName,
  ...res.middleName && { middle: res.middleName },
};

// person -> { name: "Daniel", surname: "Zotti"}
Enter fullscreen mode Exit fullscreen mode

In 2019 I bumped into this article by Andrea Simone Costa and it blew my mind, thus I recommend you take a look at it if you are interested in an in-depth explanation!

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more