0

I'm getting a query params object that may look like this:

const queryParams = { status: 'Online', name: 'Jeff', age: '35' }

I need to create a query params string out of it,

Example return value would be:

?status=Online&name=Jeff&age=35&

I wrote this function:

const getParams = (queryParams) => {
  let str = '?'
  for (key in queryParams) {
  if (queryParams[key]) {
    str+= `${key}=${queryParams[key]}&`
   }
  }
  return str
};

Is there a shorter/better way to do it than this function?

flow24
  • 793
  • 2
  • 5
  • 17
  • 1
    Note the second answer in the duplicate is the modern solution: https://stackoverflow.com/a/53171438/519413 – Rory McCrossan Jun 26 '23 at 15:26
  • @RoryMcCrossan Although your link links to the answer you mention, which answer is second depends upon the individual users currently selected sort order. – phuzi Jun 26 '23 at 15:31
  • That's true. I assumed the default sort order of highest scoring, but I also made sure to link directly to the answer. – Rory McCrossan Jun 26 '23 at 15:49

1 Answers1

1
const queryParams = { status: 'Online', name: 'Jeff', age: '35' };

function buildQueryString(params) {
  const queryString = Object.entries(params)
    .map(([key, value]) => `${key}=${value}`)
    .join('&');
  return queryString;
}

const queryString = buildQueryString(queryParams);
jiseon
  • 11
  • 3