Extend URLSearchParams to object

There must be a reason this is a bad idea or it would be included in the API, right? 😅

URLSearchParams.prototype.toObject = function() {
  return […this.keys()]
    .reduce((o,k) => ({ …o, [k]: this.get(k) }), {});
}

Sample location.href:

https://www.google.com/search?q=mdn+urlsearchparams+to+object&oq=mdn+url&aqs=chrome.2.69i59j69i57j35i39j0i512l2j69i60l3.2756j0j9&sourceid=chrome&ie=UTF-8

Usage:

qs = new URLSearchParams(location.search);
console.log(qs.toObject());

Sample output:

{
  "q": "mdn urlsearchparams to object",
  "oq": "mdn url",
  "aqs": "chrome.2.69i59j69i57j35i39j0i512l2j69i60l3.2756j0j9",
  "sourceid": "chrome",
  "ie": "UTF-8"
}

Me thinks it would be a better practice to use an external function instead:

const paramsObject = (usp) => [...usp.keys()]
  .reduce((o, k) => ({ ...o, [k]: usp.get(k) }), {});
console.log(paramsObject(new URLSearchParams(location.search)));

Leave a Reply

Your email address will not be published.