Conditionally add keys to JavaScript objects with the spread operator
In JavaScript, we can use the spread operator combined with short-circuit evaluation to conditionally add keys to an object.
Let's say that we wanted to build a JavaScript object for querying based on some filtering parameters that don't always exist. We would usually write something like this.
function buildQuery(filters) {
const queryObject = {};
if (filters.firstName) {
queryObject.firstName = filters.firstName;
}
if (filters.lastName) {
queryObject.lastName = filters.lastName;
}
if (filters.age) {
queryObject.age = filters.age;
}
return queryObject;
}
The spread operator combined with short-circuit evaluation help us to simplify our buildQuery
function.
function buildQuery(filters) {
return {
...filters.firstName && { firstName: filters.firstName },
...filters.lastName && { lastName: filters.lastName },
...filters.age && { age: filters.age },
};
};
We could also write the buildQuery
function using an arrow function.
const buildQuery = query => ({
...filters.firstName && { firstName: filters.firstName },
...filters.lastName && { lastName: filters.lastName },
...filters.age && { age: filters.age },
});
This technique can also be used outside of a function. Let's say we wanted to conditionally gather React props
into an object. We can achieve this quite easily using the spread operator combined with short-circuit evaluation.
const filters = {
city: this.props.city,
...this.props.cuisine && { cuisine: this.props.cuisine },
...this.props.category && { category: this.props.category },
};
This technique can help to simplify your JavaScript or TypeScript code for conditionally building and manipulating objects.