英文:
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论