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

如何将多级JavaScript对象转换为指定格式的查询字符串?

实现嵌套JavaScript对象到特定格式查询字符串的转换

URLSearchParams仅支持处理扁平结构的键值对,遇到嵌套对象时会直接将其转为[object Object],无法满足你的需求。要生成location%5Bokrug%5D%5B%5D=38&location%5Bokrug%5D%5B%5D=41这种格式的查询字符串,需要自己实现递归序列化逻辑:

function serializeNestedObject(obj, parentKey = '') {
  const queryParts = [];

  Object.entries(obj).forEach(([key, value]) => {
    // 拼接当前层级的键名
    const currentKey = parentKey ? `${parentKey}[${encodeURIComponent(key)}]` : encodeURIComponent(key);

    if (Array.isArray(value)) {
      // 处理数组:为每个元素生成带[]的键
      value.forEach(item => {
        queryParts.push(`${currentKey}[]=${encodeURIComponent(item)}`);
      });
    } else if (typeof value === 'object' && value !== null) {
      // 递归处理嵌套对象
      queryParts.push(serializeNestedObject(value, currentKey));
    } else {
      // 处理基本类型值
      queryParts.push(`${currentKey}=${encodeURIComponent(value)}`);
    }
  });

  return queryParts.join('&');
}

// 测试你的场景
const filter = {
  location: {
    okrug: [38, 41]
  }
};

console.log(serializeNestedObject(filter));
// 输出:location%5Bokrug%5D%5B%5D=38&location%5Bokrug%5D%5B%5D=41

函数说明

  • 递归遍历对象的所有属性,自动处理嵌套对象和数组结构
  • 对键名和值都执行encodeURIComponent编码,避免特殊字符破坏查询字符串格式
  • 数组元素会生成parentKey[]=value的格式,完全匹配你需要的查询字符串规范

内容的提问来源于stack exchange,提问作者maximos

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 20:45:37