2

I am looking at this example on the google chrome docs.

I am trying to console.log the variable params

let url = new URL('https://example.com?foo=1&bar=2'); // or construct from window.location

let params = new URLSearchParams(url.search.slice(1));

However, this is all I get:

getAll: Object {  }, has: Object {  }, set: Object {  }, sort: Object {  }, 
toString: Object {  }, entries: Object {  }, forEach: Object {  }, 
keys: Object {  }, values: Object {  } }

Like in the example, you can loop through the params variable and console.log each parameter, but not the variable params. Why can't it be logged and seen as an object?

piraha
  • 65
  • 10
  • Didn't understand if this is what you mean but you have to iterate throw the `params` variable in order to see the results (as shown in the example you shared). It appears as empty due to is not an object and it does not work the same way, `params` is an instance of `URLSearchParams`. – Luka Cerrutti Apr 04 '22 at 18:31
  • When you loop over params with a for loop, you only see enumerable properties. However the object contains other properties that are not enumerable, but you do see them when you console.log the whole object. – James Apr 04 '22 at 19:08
  • Ah @LukaCerrutti that's what I didn't get, that `params` isn't really an object, but an instance of `URLSearchParams`. I thought that if I can loop through it like an object, it then must be an object. – piraha Apr 05 '22 at 17:17

2 Answers2

2

You can use fromEntries

let url = new URL('https://example.com?foo=1&bar=2'); // or construct from window.location
let params = new URLSearchParams(url.search.slice(1));
console.log(Object.fromEntries(params)) // outputs {foo: '1', bar: '2'}
tony
  • 1,274
  • 1
  • 11
  • 27
1

The way I got this to work was:

  1. Go to the following url: https://example.com/?foo=1&bar=2
  2. Open dev tools in Chrome (or your favorite browser) and drop the following code into the console:

let url = window.location.search;

let searchParams = new URLSearchParams(url);

let foo = searchParams.get('foo');
let bar = searchParams.get('bar');

console.log(foo, bar)

Output should be 1 2

Gabe
  • 28
  • 5