Skip to content

Commit df6abd7

Browse files
authored
Snippet now checks the length of the queryString to decide if it should use ? or &
1 parent 72f63bd commit df6abd7

File tree

1 file changed

+2
-2
lines changed

1 file changed

+2
-2
lines changed

snippets/objectToQueryString.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,14 @@ tags: utility,object,function,intermediate
66
Returns a query string generated from the key-value pairs of the given object.
77

88
Use `Array.prototype.reduce()` on `Object.entries(queryParameters)` to create the query string.
9-
Determine the `symbol` to be either `?` or `&` based on the `index` and concatenate `val` to `queryString` only if it's a string.
9+
Determine the `symbol` to be either `?` or `&` based on the `length` of `queryString` and concatenate `val` to `queryString` only if it's a string.
1010
Return the `queryString` or an empty string when the `queryParameters` are falsy.
1111

1212
```js
1313
const objectToQueryString = queryParameters => {
1414
return queryParameters
1515
? Object.entries(queryParameters).reduce((queryString, [key, val], index) => {
16-
const symbol = index === 0 ? '?' : '&';
16+
const symbol = queryString.length === 0 ? '?' : '&';
1717
queryString += typeof val === 'string' ? `${symbol}${key}=${val}` : '';
1818
return queryString;
1919
}, '')

0 commit comments

Comments
 (0)