Bird
0
0

Given the object { search: 'books', page: 2, filter: '' }, which code snippet correctly creates a query string excluding keys with empty values using URLSearchParams?

hard📝 Application Q8 of 15
Node.js - URL and Query String Handling
Given the object { search: 'books', page: 2, filter: '' }, which code snippet correctly creates a query string excluding keys with empty values using URLSearchParams?
Aconst params = new URLSearchParams(); for (const key in obj) { params.append(key, obj[key]); }
Bconst params = new URLSearchParams(obj); // automatically excludes empty values
Cconst params = new URLSearchParams(Object.entries(obj).filter(([_, v]) => v !== ''));
Dconst params = new URLSearchParams(); params.set('search', obj.search); params.set('page', obj.page);
Step-by-Step Solution
Solution:
  1. Step 1: Identify the need to exclude empty values

    We must filter out keys with empty string values before creating URLSearchParams.
  2. Step 2: Analyze options

    const params = new URLSearchParams(Object.entries(obj).filter(([_, v]) => v !== '')); filters entries where value is not empty, then passes to URLSearchParams.
  3. Step 3: Why others are incorrect

    B does not exclude empty values automatically; C appends all keys including empty; D manually sets only some keys, not scalable.
  4. Final Answer:

    const params = new URLSearchParams(Object.entries(obj).filter(([_, v]) => v !== '')); -> Option C
  5. Quick Check:

    Filter entries before passing to URLSearchParams to exclude empty values. [OK]
Quick Trick: Filter out empty values before creating URLSearchParams [OK]
Common Mistakes:
  • Assuming URLSearchParams excludes empty values automatically
  • Appending all keys without filtering
  • Manually setting keys without handling all object properties

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes