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?

3
  • 1
    Note the second answer in the duplicate is the modern solution: stackoverflow.com/a/53171438/519413 Commented Jun 26, 2023 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. Commented Jun 26, 2023 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. Commented Jun 26, 2023 at 15:49

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.