You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 01:02:04