URLSearchParams嵌套对象与查询字符串相互转换的异常问题
嵌套对象与嵌套格式查询字符串的相互转换方案
原生URLSearchParams仅支持扁平的键值对结构,无法直接处理嵌套对象或数组生成location[okrug][]=38&location[okrug][]=41这类格式的查询字符串,也无法反向解析这类字符串为嵌套对象。以下是手动实现双向转换的方案:
一、嵌套对象转符合格式的查询字符串
实现递归函数遍历对象嵌套结构,生成正确的键名格式:
function objectToQueryString(obj, parentKey = '') { const params = []; for (const key in obj) { if (obj.hasOwnProperty(key)) { const currentKey = parentKey ? `${parentKey}[${key}]` : key; const value = obj[key]; if (Array.isArray(value)) { // 处理数组,生成key[]=value格式 value.forEach(item => { params.push(`${encodeURIComponent(currentKey)}[]=${encodeURIComponent(item)}`); }); } else if (typeof value === 'object' && value !== null) { // 递归处理嵌套对象 params.push(objectToQueryString(value, currentKey)); } else { // 普通键值对 params.push(`${encodeURIComponent(currentKey)}=${encodeURIComponent(value)}`); } } } return params.join('&'); } // 测试 const filter = { location: { okrug: [38, 41] } }; console.log(objectToQueryString(filter)); // 输出:location[okrug][]=38&location[okrug][]=41
二、嵌套格式查询字符串转嵌套对象
解析查询字符串的键名结构,将值映射到对应嵌套层级:
function queryStringToObject(queryStr) { const obj = {}; const params = new URLSearchParams(queryStr); for (const [key, value] of params) { // 拆分键的层级,比如location[okrug][]拆分成['location', 'okrug', ''] const keys = key.match(/([^\[\]]+)/g) || []; let current = obj; for (let i = 0; i < keys.length; i++) { const k = keys[i]; // 处理数组标记(空字符串对应[]) if (i === keys.length - 1 && k === '') { // 确保父级是数组 const parentKeys = keys.slice(0, -1); let parent = obj; for (let j = 0; j < parentKeys.length; j++) { const pk = parentKeys[j]; if (!parent[pk]) parent[pk] = []; parent = parent[pk]; } parent.push(decodeURIComponent(value)); } else { // 处理普通对象键 if (!current[k]) { current[k] = (i === keys.length - 1) ? decodeURIComponent(value) : {}; } current = current[k]; } } } return obj; } // 测试 const queryStr = 'location[okrug][]=38&location[okrug][]=41'; console.log(queryStringToObject(queryStr)); // 输出:{ location: { okrug: [ '38', '41' ] } } // 如需数字类型可自行添加值类型转换逻辑
补充说明
- 上述函数支持多层嵌套对象和数组的混合结构,可根据实际需求扩展类型转换、特殊字符处理等逻辑。
- 若仅需处理特定结构(如示例中的二级嵌套+数组),可简化递归逻辑以提升性能。
内容的提问来源于stack exchange,提问作者maximos
相关产品推荐
相关产品推荐

