(obj: Record<string, string | string[] | undefined>, prefix?: string)
| 1 | export const objectToSearchParameters = (obj: Record<string, string | string[] | undefined>, prefix?: string) => { |
| 2 | const params = new URLSearchParams() |
| 3 | |
| 4 | for (const key in obj) { |
| 5 | const value = obj[key] |
| 6 | const prefixedKey = prefix ? `${prefix}[${key}]` : key |
| 7 | |
| 8 | if (value === undefined) continue |
| 9 | if (Array.isArray(value)) { |
| 10 | // 如果值是数组,展开数组每个元素为单独的键值对 |
| 11 | value.forEach((item, index) => { |
| 12 | params.append(`${prefixedKey}[${index}]`, item) |
| 13 | }) |
| 14 | } else if (value !== null && typeof value === 'object') { |
| 15 | // 如果值是对象,递归处理 |
| 16 | params.append(prefixedKey, JSON.stringify(value)) // 将嵌套对象转换为字符串 |
| 17 | } else { |
| 18 | // 否则,直接添加键值对 |
| 19 | params.append(prefixedKey, value) |
| 20 | } |
| 21 | } |
| 22 | |
| 23 | return params |
| 24 | } |
nothing calls this directly
no outgoing calls
no test coverage detected