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' }
asked Aug 13, 2019 at 17:23
\$\endgroup\$
0

2 Answers 2

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

answered Aug 13, 2019 at 17:57
\$\endgroup\$
1
  • \$\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\$ Commented Aug 13, 2019 at 18:03
4
\$\begingroup\$

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

answered Jan 15, 2021 at 12:20
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.