JavaScript — How to Convert URLSearchParams to Object

Modern JavaScript ships with the dedicated URLSearchParams class to interact with URL query parameters. This class parses query parameters from a given string and provides methods to interact with the parameters. For example, you may append, delete, get, sort, or iterate through all items using the forEach, keys, or values methods.

But the URLSearchParams class doesn’t provide a toObject() method. This tutorial shows you how to convert a URL search parameters instance to a plain JavaScript object.

Node.js Series Overview

Convert URLSearchParams to a JavaScript Object

Use the Object.fromEntries method and pass the URLSearchParams instance as an argument. This creates a JavaScript object from the parsed query parameters:

const params = Object.fromEntries(  
  new URLSearchParams(window.location.search)
)

// URL: example.com/path?foo=bar&name=futurestudio&num=1
// { foo: 'bar', name: 'futurestudio', num: '1' }

Here’s how it works: the URLSearchParams class implements JavaScript’s iterator interface. The iterator interface contains the Iterator#entries method. This entries methods returns an iterator providing an array of [key, value] pairs:

const params = new URLSearchParams('?foo=bar&name=futurestudio&num=1')

const iterator = params.entries()

iterator.next()  
// { done: false, value: ['foo', 'bar'] } 

iterator.next()  
// { done: false, value: ['name', 'futurestudio'] } 

iterator.next()  
// { done: false, value: ['num', '1] } 

iterator.next()  
// { done: true, value: undefined } 

The Object.fromEntries method then iterates over all key-value pairs and creates the object until the iterator is done.

Awesome!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.