Conditionally add keys to JavaScript objects with the spread operator

Discover how to conditionally add keys to JavaScript objects with the spread operator.
December 26, 2020JavaScript
2 min read

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.

New
Be React Ready

Learn modern React with TypeScript.

Learn modern React development with TypeScript from my books React Ready and React Router Ready.