Files
30-seconds-of-code/snippets/js/s/query-string-to-object.md
2023-05-07 16:07:29 +03:00

764 B

title, type, language, tags, cover, dateModified
title type language tags cover dateModified
Query string to object snippet javascript
object
dark-mode 2020-11-03T22:11:18+02:00

Generates an object from the given query string or URL.

  • Use String.prototype.split() to get the params from the given url.
  • Use the URLSearchParams constructor to create an appropriate object and convert it to an array of key-value pairs using the spread operator (...).
  • Use Array.prototype.reduce() to convert the array of key-value pairs into an object.
const queryStringToObject = url =>
  [...new URLSearchParams(url.split('?')[1])].reduce(
    (a, [k, v]) => ((a[k] = v), a),
    {}
  );
queryStringToObject('https://google.com?page=1&count=10');
// {page: '1', count: '10'}