1
\$\begingroup\$

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' }
\$\endgroup\$
2
\$\begingroup\$

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);

\$\endgroup\$
  • \$\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 at 18:03

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.