π 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 },
};
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"}
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)