更好的方法来动态创建查询字符串

huangapple go评论57阅读模式
英文:

Better way to create query string dynamically

问题

Sure, here's the translated code part:

我收到一个可能如下所示的查询参数对象

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

我需要将其转换为查询参数字符串

示例返回值将是

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

我编写了以下函数

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

是否有比这个函数更短/更好的方法

Please note that I've translated the code and the relevant text while omitting the parts you requested not to be translated.

英文:

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?

答案1

得分: 1

const queryParams = { status: '在线', name: 'Jeff', age: '35' };

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

const queryString = buildQueryString(queryParams);
英文:
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);

huangapple
  • 本文由 发表于 2023年6月26日 23:19:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76558059.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定