How to get all query string parameters as an object in JavaScript

sachin
edited January 2023 in javascript

I have get parameters like this: ?size=M&price=29&sort=desc I wants to convert it to json object as follows:

{ size: 'M', price: '29', sort: 'desc' }
Tagged:

Answers

  • In JavaScript, you can use the URLSearchParams interface to convert a query string into an object. It provides utility methods to work with the query string of a URL.

    1. Pass the query string to the URLSearchParams constructor to turn it into an object instance.
    2. Use the get() method to access query string parameters.
    3. To get a native JavaScript object, pass the object instance to the Object.fromEntries() method.
    const qs = `?size=M&price=29&sort=desc`
    
    const params = new URLSearchParams(qs)
    
    console.log(params.get('size')) // M
    console.log(params.get('price')) // 29
    console.log(params.get('sort')) // desc
    
    // Convert to native JS object
    const obj = Object.fromEntries(params)
    console.log(obj)
    // { size: 'M', price: '29', sort: 'desc' }
    


Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!