There are several ways to conditionally set object properties.
Let’s assume we want to copy all the properties of the formValues
object below into a user
object. However, the email
property should only be included if the top-level domain ends in .com
.
const formValues = {
fullname: "John Doe",
username: "johnny_d",
email: "hi@johndoe", // this is intentional :(
};
Spread operator
With this we first isolate the email
property from the rest, test it for inclusion, and use the spread operator to copy formValues
into user
.
// 1. Isolate
const { email, ...otherFormValues } = formValues;
// 2. Test
const includeEmail = email.endsWith(".com");
// 3. Spread
const user = {
...otherFormValues,
...(includeEmail ? { email } : {}),
};
Using an if
statement
Here, we first copy the unconditional properties from formValues
i.e. fullname
and username
into the user object. Then we test the email
for inclusion. And finally update the user
object.
// 1. Copy
const user = {
fullname: formValues.fullname,
username: formValues.username,
};
// 2. Test
if (formValues.email.endsWith(".com")) {
// 3. Update
user.email = formValues.email;
}
Using the if
statement method can immediately get unwieldy and ineffective because we are manually adding the unconditonal properties. To avoid this, you can map through formValues
like so:
let user = {};
for (let key in formValues) {
if (key === "email" && !formValues[key].endsWith(".com")) {
continue;
}
user[key] = formValues[key];
}
Object.assign
This can seem needlessly preposterous at first glance but can be faster for larger objects.
let user = {};
for (let key in formValues) {
if (key === "email" && !formValues[key].endsWith(".com")) {
continue;
}
Object.assign(user, { [key]: formValues[key] });
}
Final verdict
I often reach for the spread method whenever I can because it tends to be more readable and deductive at a glance. However, for your use case, it is also important to consider other aspects like performance and browser support.
Typically though, you need not worry. But you probably should.