Home > Mobile >  Pass object to URL search params
Pass object to URL search params

Time:06-11

I want to pass this object to url search params:

const obj = {
 mb_brand: car.base,
 mb_factor: car.factor,
 mb_type: car.type
}

I have function to set params:

const setQuery = (key, value) => {
        let obj_url = new URL(window.location.href);
        let params = obj_url.searchParams;
        params.set(key, value);

        Router.push({
            pathname: obj_url.pathname,
            search: obj_url.search
        });
    }

And what I tried so far is:

for(let i = 0 ; i < Object.keys(obj).length ; i  ){
   setQuery(Object.keys(obj)[i], Object.values(obj)[i])
}

But it just set 1 parameter not 3.

const obj = {
  mb_brand: 'blah',
  mb_factor: 'blah',
  mb_type: 'blah'
}


const setQuery = (key, value) => {
  let obj_url = new URL(window.location.href);
  let params = obj_url.searchParams;
  params.set(key, value);

  /*Router.push({
      pathname: obj_url.pathname,
      search: obj_url.search
  });*/

  console.log(obj_url.search)
}


for (let i = 0; i < Object.keys(obj).length; i  ) {
  setQuery(Object.keys(obj)[i], Object.values(obj)[i])
}

But it set just last param.

I want to see this result on url:

localhost/index?mb_brand=blah&mb_factor=blah&?mb_type=blah

CodePudding user response:

You are defining your params variable again and again because the setQuery is being called inside a loop, and overwriting the previous query param. Hence, only the last param is available. Define these variables outside of the searchQuery, so that the for loop can append the params to the same variable.

const obj = {
  mb_brand: 'blah',
  mb_factor: 'blah',
  mb_type: 'blah'
}

let obj_url = new URL(window.location.href);
let params = obj_url.searchParams;

const setQuery = (key, value) => {

  params.set(key, value);

  // console.log(obj_url.search)
}


for (let i = 0; i < Object.keys(obj).length; i  ) {
  setQuery(Object.keys(obj)[i], Object.values(obj)[i])
}

/*Router.push({
          pathname: obj_url.pathname,
          search: obj_url.search
      });*/

console.log(params.toString());

Console output:

mb_brand=blah&mb_factor=blah&mb_type=blah

CodePudding user response:

You can directly build search params from an object, see https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams:

// Search parameters can also be an object
const paramsObj = {foo: 'bar', baz: 'bar'};
const searchParams = new URLSearchParams(paramsObj);

searchParams.toString();                 // "foo=bar&baz=bar"
searchParams.has('foo');                 // true
searchParams.get('foo'); 

  • Related