Destructuring

Add and conditionally override a property of an object.


const object = { ...(someCondition && { key: "value" }) };
js

Context

In development, we often face a situation where we have to instantiate or modify the properties of an object conditionally.

Let's say we are looking for a user by email, last name and/or first name.

In most cases, a query with a falsy property value such as null or undefined will not return anything good so we have to add them conditionally based on the argument's presence.

Usage

// Add a property conditionally
let object = { ...(true && { key: "value" }) }; // { key: "value" }

// Override a property conditionally
object = { key: 1, ...(true && { key: 2 }) }; // { key: 2 }
object = { key: 1, ...(false && { key: 2 }) }; // { key: 1 }
js

Explanation

So back to our example, if we want to filter users based on multiple parameters we better only apply every parameter that is actually given in order to avoid returning every user with a specific lastname that also has null as a firstname and email as we didn't provide them.

To do so, we have to add each parameters based on there presence, the first method that might come through your mind is using a simple conditional like this:

const body = {};
const query = {};

if (body.email) {
  query.email = body.email;
}
if (body.lastname) {
  query.lastname = body.lastname;
}
if (body.firstname) {
  query.firstname = body.firstname;
}
// query = {}
js

But why not take advantage of one of the best features brought up by ES6: Destructuring.

For those who don't know how it works, destructuring basically allows you to extract the elements of an array or an object, so in our case let's say we have a search query for a user with a specific lastname:

const body = {
  lastname: "Doe"
};

const query = {
  ...(body.email && { email: body.email }),
  ...(body.lastname && { lastname: body.lastname }),
  ...(body.firstname && { firstname: body.firstname }),
}; // { lastname: "Doe" }
js

As you can see only the lastname parameter is added to the query object, allowing us to return every user with "Doe" as a lastname and leaving out the condition where firstname and email are both null as there are falsy.

Conclusion

Here you have it a concise solution to conditionally add properties to an object based on any condition you'd like here we just went for their presence. The final refactored result would look like this:

const query = {
  ...(email && { email }),
  ...(lastname && { lastname }),
  ...(firstname && { firstname }),
};
js

Last updated: October 14, 2022

⚡ Who am i to talk about this? ⚡

Honestly i am no one, i've just been coding for 3 years now and i like to document every solutions to every problem i encounter. Extracting as much code snippets and tutorials i can so that if i ever need it again i just have to pop back here and get a quick refresher.

Feel free to me through this learning journey by providing any feedback and if you wanna support me: