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' }
2 Answers 2
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– 3limin4t0r2019年08月13日 18:03:02 +00:00Commented Aug 13, 2019 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;
Object.fromEntries(params);
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 :)