如何在JavaScript中构造稀疏字段集格式的URL查询参数
构造含稀疏字段集的URL参数方法
原生的URLSearchParams无法直接处理嵌套对象的参数转换,要生成type[name]=s这种格式的参数,得自己实现一个递归处理函数,把嵌套结构的键名转换成目标格式。
实现代码
function buildSearchParams(obj, parentKey = '') { const params = new URLSearchParams(); for (const key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { const currentKey = parentKey ? `${parentKey}[${key}]` : key; const value = obj[key]; if (typeof value === 'object' && value !== null && !Array.isArray(value)) { // 递归处理嵌套对象 Object.assign(params, buildSearchParams(value, currentKey)); } else { params.append(currentKey, value); } } } return params; } // 测试给定的page对象 const page = { limit: 0, offset:10, type: { name: 's', age:'n' } }; const searchParams = buildSearchParams(page); const targetUrl = `https://sample.run/api/product?${searchParams.toString()}`; console.log(targetUrl);
输出结果
运行后会生成目标URL:
https://sample.run/api/product?limit=0&offset=10&type[name]=s&type[age]=n
内容的提问来源于stack exchange,提问作者skyshine
相关产品推荐
相关产品推荐

