[javascript] How to convert URL parameters to a JavaScript object?

Here is a more-streamlined version of silicakes' approach.

The following function(s) can parse a querystring from either a USVString or Location.

_x000D_
_x000D_
/**
 * Returns a plain object representation of a URLSearchParams object.
 * @param {USVString} search - A URL querystring
 * @return {Object} a key-value pair object from a URL querystring
 */
const parseSearch = (search) =>
  [...new URLSearchParams(search).entries()]
    .reduce((acc, [key, val]) => ({
      ...acc,
      // eslint-disable-next-line no-nested-ternary
      [key]: Object.prototype.hasOwnProperty.call(acc, key)
        ? Array.isArray(acc[key])
          ? [...acc[key], val]
          : [acc[key], val]
        : val
    }), {});

/**
 * Returns a plain object representation of a URLSearchParams object.
 * @param {Location} location - Either a document or window location, or React useLocation()
 * @return {Object} a key-value pair object from a URL querystring
 */
const parseLocationSearch = (location) => parseSearch(location.search);

console.log(parseSearch('?foo=bar&x=y&ids=%5B1%2C2%2C3%5D&ids=%5B4%2C5%2C6%5D'));
_x000D_
.as-console-wrapper { top: 0; max-height: 100% !important; }
_x000D_
_x000D_
_x000D_

Here is a one-liner of the code above (125 bytes):

Where f is parseSearch

f=s=>[...new URLSearchParams(s).entries()].reduce((a,[k,v])=>({...a,[k]:a[k]?Array.isArray(a[k])?[...a[k],v]:[a[k],v]:v}),{})

Edit

Here is a method of serializing and updating:

_x000D_
_x000D_
const parseSearch = (search) =>
  [...new URLSearchParams(search).entries()]
    .reduce((acc, [key, val]) => ({
      ...acc,
      // eslint-disable-next-line no-nested-ternary
      [key]: Object.prototype.hasOwnProperty.call(acc, key)
        ? Array.isArray(acc[key])
          ? [...acc[key], val]
          : [acc[key], val]
        : val
    }), {});

const toQueryString = (params) =>
  `?${Object.entries(params)
    .flatMap(([key, values]) =>
      Array.isArray(values)
        ? values.map(value => [key, value])
        : [[key, values]])
    .map(pair => pair.map(val => encodeURIComponent(val)).join('='))
    .join('&')}`;

const updateQueryString = (search, update) =>
  (parsed =>
    toQueryString(update instanceof Function
      ? update(parsed)
      : { ...parsed, ...update }))
  (parseSearch(search));

const queryString = '?foo=bar&x=y&ids=%5B1%2C2%2C3%5D&ids=%5B4%2C5%2C6%5D';
const parsedQuery = parseSearch(queryString);
console.log(parsedQuery);
console.log(toQueryString(parsedQuery) === queryString);

const updatedQuerySimple = updateQueryString(queryString, {
  foo: 'baz',
  x: 'z',
});
console.log(updatedQuerySimple);
console.log(parseSearch(updatedQuerySimple));

const updatedQuery = updateQueryString(updatedQuerySimple, parsed => ({
  ...parsed,
  ids: [
    ...parsed.ids,
    JSON.stringify([7,8,9])
  ]
}));
console.log(updatedQuery);
console.log(parseSearch(updatedQuery));
_x000D_
.as-console-wrapper { top: 0; max-height: 100% !important; }
_x000D_
_x000D_
_x000D_

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to url

What is the difference between URL parameters and query strings? Allow Access-Control-Allow-Origin header using HTML5 fetch API File URL "Not allowed to load local resource" in the Internet Browser Slack URL to open a channel from browser Getting absolute URLs using ASP.NET Core How do I load an HTTP URL with App Transport Security enabled in iOS 9? Adding form action in html in laravel React-router urls don't work when refreshing or writing manually URL for public Amazon S3 bucket How can I append a query parameter to an existing URL?

Examples related to url-parameters

What is the difference between URL parameters and query strings? RestTemplate: How to send URL and query parameters together How can I get query parameters from a URL in Vue.js? How can I get the named parameters from a URL using Flask? How to get a URL parameter in Express? PHP check if url parameter exists Pass Hidden parameters using response.sendRedirect() How to convert URL parameters to a JavaScript object? How to replace url parameter with javascript/jquery? Username and password in https url

Examples related to url-parsing

How to get parameters from a URL string? How to convert URL parameters to a JavaScript object? Change URL parameters