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
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({}));
{ 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!