DEV Community

Melvinvmegen
Melvinvmegen

Posted on • Originally published at blog.melvinvmegen.com on

Use Javascript Destructuring to add and conditionally override a property of an object.

Image description

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 }
Enter fullscreen mode Exit fullscreen mode

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 = {}
Enter fullscreen mode Exit fullscreen mode

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" } 
Enter fullscreen mode Exit fullscreen mode

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 }),
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)