skip to Main Content

I want to convert the searchParams function into an object? like this =>>>
URLSearchParams { ‘title’ => ‘1’ } to { title : 1 }

I want this to be done for everything in the URLSearchParams, not just one value

i get and push to object like this

 const url = { title: "" };  
 url.title=req.nextUrl.searchParams.get("title");

but i want for any value

2

Answers


  1. There doesn’t appear to be a trivial way to do this, but one could write a function pretty easily to convert a URLSearchParams object to a standard object:

    function paramsToObject(searchParams) {
        let obj = {};
        for (const [key, value] of searchParams.entries()) {
            obj[key] = value;
        }
        return obj;
    }
    
    Login or Signup to reply.
  2. I think the most straight-forward way would be this:

    const searchParams = new URLSearchParams();
    searchParams.set( 'title', 'blub' );
    
    const obj = Object.fromEntries( searchParams.entries() );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search