如何将多级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
相关产品推荐
相关产品推荐

