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)