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

\$\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\$
    – 3limin4t0r
    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 :)

\$\endgroup\$

Your Answer

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

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