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

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

Better way to create query string dynamically

问题

Sure, here's the translated code part:

  1. 我收到一个可能如下所示的查询参数对象
  2. const queryParams = { status: 'Online', name: 'Jeff', age: '35' }
  3. 我需要将其转换为查询参数字符串
  4. 示例返回值将是
  5. ?status=Online&name=Jeff&age=35&
  6. 我编写了以下函数
  7. const getParams = (queryParams) => {
  8. let str = '?'
  9. for (key in queryParams) {
  10. if (queryParams[key]) {
  11. str += `${key}=${queryParams[key]}&`
  12. }
  13. }
  14. return str
  15. };
  16. 是否有比这个函数更短/更好的方法

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:

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

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

Example return value would be:

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

I wrote this function:

  1. const getParams = (queryParams) => {
  2. let str = '?'
  3. for (key in queryParams) {
  4. if (queryParams[key]) {
  5. str+= `${key}=${queryParams[key]}&`
  6. }
  7. }
  8. return str
  9. };

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

答案1

得分: 1

  1. const queryParams = { status: '在线', name: 'Jeff', age: '35' };
  2. function buildQueryString(params) {
  3. const queryString = Object.entries(params)
  4. .map(([key, value]) => `${key}=${value}`)
  5. .join('&');
  6. return queryString;
  7. }
  8. const queryString = buildQueryString(queryParams);
英文:
  1. const queryParams = { status: 'Online', name: 'Jeff', age: '35' };
  2. function buildQueryString(params) {
  3. const queryString = Object.entries(params)
  4. .map(([key, value]) => `${key}=${value}`)
  5. .join('&');
  6. return queryString;
  7. }
  8. 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:

确定