JavaScriptFundamental (ES6), part 2
Convert an object to a query string in JavaScript
104 An object to a query string, and back again
fairTurn a filter object into a query string with URLSearchParams — dropping the keys that were not set, repeating a key for each value in an array — and then parse it back into an object. Assert what the encoding does to a space and to a comma, and be clear about the two things the round trip cannot preserve.
Stuck? Three hints, smallest first
- 1.
appendadds another value under the same key;setreplaces. An array wantsappendper item. - 2. Reading back,
getAll(key)gives every value for that key, so a repeat is how an array survives. - 3. Everything in a query string is text. Nothing else survives the trip.
function toQuery(params) {
const search = new URLSearchParams();
for (const [key, value] of Object.entries(params)) {
if (value === undefined || value === null) continue; // absent, not empty
if (Array.isArray(value)) {
for (const item of value) search.append(key, String(item));
continue;
}
search.set(key, String(value));
}
return search.toString();
}
function fromQuery(query, arrayKeys = []) {
const search = new URLSearchParams(query);
const out = {};
for (const key of new Set(search.keys())) {
const all = search.getAll(key);
out[key] = all.length > 1 || arrayKeys.includes(key) ? all : all[0];
}
return out;
}
const filters = {
q: 'gari, 5kg',
city: 'Lagos',
page: 2,
active: true,
tag: ['fresh', 'bulk'],
note: '',
skip: null,
gone: undefined,
sign: '\u20a6',
};
const query = toQuery(filters);
const back = fromQuery(query);
const types = [typeof back.page, typeof back.active, back.page, back.active];
const droppedKeys = ['skip' in back, 'gone' in back, 'note' in back];
const oneTag = fromQuery(toQuery({ tag: ['fresh'] }));
const oneTagDeclared = fromQuery(toQuery({ tag: ['fresh'] }), ['tag']);
const spaceEncoding = [query.includes('gari%2C+5kg'), back.q];
const nairaEncoding = [query.includes('sign=%E2%82%A6'), back.sign];
console.log('query :', query);
console.log('back :', back);
console.log('types :', types);
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the query string repeats the key for an array and skips what was not set', query, 'q=gari%2C+5kg&city=Lagos&page=2&active=true&tag=fresh&tag=bulk¬e=&sign=%E2%82%A6');
test('a space becomes a plus and a comma is percent-encoded, both decoding back exactly', spaceEncoding, [true, 'gari, 5kg']);
test('a repeated key comes back as an array', back.tag, ['fresh', 'bulk']);
test('null and undefined are dropped, while an empty string is kept as a real value', [droppedKeys, back.note], [[false, false, true], '']);
test('every value comes back a string: the number and the boolean are gone', types, ['string', 'string', '2', 'true']);
test('a one-element array degrades to a scalar unless you say the key is a list', [oneTag.tag, oneTagDeclared.tag], ['fresh', ['fresh']]);
test('non-ASCII is percent-encoded as UTF-8 and survives the trip', nairaEncoding, [true, '\u20a6']);
test('and the whole object round-trips as long as you expect strings', back, { q: 'gari, 5kg', city: 'Lagos', page: '2', active: 'true', tag: ['fresh', 'bulk'], note: '', sign: '\u20a6' });
URLSearchParams is the right tool and it has one surprise worth knowing: it encodes a space as +, not %20, because it implements the application/x-www-form-urlencoded rules rather than generic percent-encoding. That is correct for a query string and correct on the way back — its parser reads + as a space — but it means hand-rolling one half with encodeURIComponent, which produces %20, and the other half with URLSearchParams works by luck, and breaks on a literal plus sign in a value.
The fifth assertion is the limit of the format. A query string is text, so page: 2 comes back as '2' and active: true as 'true' — and 'false' is a truthy string, which is the bug this produces in practice. Coerce at the edge, per key, with something that knows what each key should be; do not hope that if (params.active) means what it looks like.
The sixth is the ambiguity nothing can fix. One value is indistinguishable from a one-element list once it is on the wire, so the reader has to be told which keys are lists — hence the arrayKeys argument. The alternative conventions each cost something: tag[]=fresh is a PHP-ism many servers do not parse, and tag=fresh,bulk falls over the first time a value contains a comma, which the q field here does. Dropping null and undefined while keeping '' is the other deliberate line. An absent filter and a filter set to the empty string mean different things to a search endpoint, and note= in the URL is how you say the second one.