diff --git a/README.md b/README.md index 7f583154b..c6bcb3855 100644 --- a/README.md +++ b/README.md @@ -615,13 +615,14 @@ const unique = arr => [...new Set(arr)]; ### URL parameters -Use `match()` with an appropriate regular expression to get all key-value pairs, `map()` them appropriately. -Combine all key-value pairs into a single object using `Object.assign()` and the spread operator (`...`). +Use `match()` with an appropriate regular expression to get all key-value pairs, `Array.reduce()` to map and combine them into a single object. Pass `location.search` as the argument to apply to the current `url`. ```js const getUrlParameters = url => - Object.assign(...url.match(/([^?=&]+)(=([^&]*))?/g).map(m => {[f,v] = m.split('='); return {[f]:v}})); + url.match(/([^?=&]+)(=([^&]*))?/g).reduce( + (a,v) => (a[v.slice(0,v.indexOf('='))] = v.slice(v.indexOf('=')), a), {} + ); // getUrlParameters('http://url.com/page?name=Adam&surname=Smith') -> {name: 'Adam', surname: 'Smith'} ``` diff --git a/snippets/URL-parameters.md b/snippets/URL-parameters.md index 4620513dc..42a43cc22 100644 --- a/snippets/URL-parameters.md +++ b/snippets/URL-parameters.md @@ -1,11 +1,12 @@ ### URL parameters -Use `match()` with an appropriate regular expression to get all key-value pairs, `map()` them appropriately. -Combine all key-value pairs into a single object using `Object.assign()` and the spread operator (`...`). +Use `match()` with an appropriate regular expression to get all key-value pairs, `Array.reduce()` to map and combine them into a single object. Pass `location.search` as the argument to apply to the current `url`. ```js const getUrlParameters = url => - Object.assign(...url.match(/([^?=&]+)(=([^&]*))?/g).map(m => {[f,v] = m.split('='); return {[f]:v}})); + url.match(/([^?=&]+)(=([^&]*))?/g).reduce( + (a,v) => (a[v.slice(0,v.indexOf('='))] = v.slice(v.indexOf('=')), a), {} + ); // getUrlParameters('http://url.com/page?name=Adam&surname=Smith') -> {name: 'Adam', surname: 'Smith'} ```