Is there a shorter / cleaner way of creating a plain object from URLSearchParams than this:

const uri = new URL('https://tempuri.org/?token=secret&test=true')
const result = {}
for (let p of uri.searchParams) {
  result[p[0]] = p[1]

Expected result:

{ token: 'secret', test: 'true' }

You could use the forEach method of URLSearchParams. Or convert it to an array using Array.from() (the spread operator would also work [...uri.searchParams] if you prefer that syntax) and use reduce.

const uri = new URL('https://tempuri.org/?token=secret&test=true');

const result1 = {};
uri.searchParams.forEach((value, key) => (result1[key] = value));
console.log("result1", result1);

const result2 = Array.from(uri.searchParams)
  .reduce((object, [key, value]) => (object[key] = value, object), {});
console.log("result2", result2);

  • \$\begingroup\$ Of course you can also use smaller variable names to reduce the size if you like. .reduce((o, [k, v]) => (o[k] = v, o), {}) I left them larger making the code better understandable (but taking up more space). \$\endgroup\$ – 3limin4t0r Aug 13 '19 at 18:03

Since ES6 there is a cleaner solution with Object.fromEntries:

const url = 'https://tempuri.org/?token=secret&test=true';
const params = new URL(url).searchParams;

It will output an object like this:

{ token: 'secret', test: 'true' }

See browser compatibility of Object.fromEntries on MDN. Basically all browsers and Node.js 12+ except Samsung Internet, Opera Android, and Internet Explorer. Time to say goodbye to the old browsers :)


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.