LearnFrenzy
Sign in Take a free test

Spread and Rest Operators · Spread and Rest Coding Problems · Question 8

Build a search query with conditional spread in JavaScript Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

Build a query object from search filters, including each property only when the filter has a meaningful value, using conditional spread.

Solution
main.js
function buildQuery({ text, category, minPrice, maxPrice, inStock }) {
  return {
    ...(text?.trim() && { q: text.trim() }),
    ...(category && category !== "all" && { category }),
    ...(minPrice != null && { minPrice }),
    ...(maxPrice != null && { maxPrice }),
    ...(inStock && { inStock: true }),
  };
}

console.log(buildQuery({ text: "  headphones ", category: "all", minPrice: 0, inStock: true }));
console.log(buildQuery({ category: "books", maxPrice: 500 }));
console.log(buildQuery({}));

Output Verified by running it on Node.js

{ q: 'headphones', minPrice: 0, inStock: true }
{ category: 'books', maxPrice: 500 }
{}

Each condition evaluates to an object or a falsy value; spreading falsy values adds nothing. minPrice uses != null so that a real 0 is kept.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links