javascriptbrowserurlsearchparams

How to log the result of "new URLSearchParams()"?


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?


Solution

  • 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'}