diff --git a/src/utils/url.ts b/src/utils/url.ts index f87460f2..d0aa43b2 100644 --- a/src/utils/url.ts +++ b/src/utils/url.ts @@ -5,43 +5,43 @@ * view the LICENSE file that was distributed with this source code. */ +import { isObject } from 'smob'; + export function buildURLQueryString(data?: any, withQuestionMark = true) { if (typeof data === 'undefined' || data === null) return ''; // If the data is already a string, return it as-is - if (typeof (data) === 'string') return data; + if (typeof data === 'string') return data; // Create a query array to hold the key/value pairs - const query = []; + const query : string[] = []; // Loop through the data object const keys = Object.keys(data); for (let i = 0; i < keys.length; i++) { - if (Object.prototype.hasOwnProperty.call(data, keys[i])) { - let value = data[keys[i]]; - - if (value && typeof value === 'object' && value.constructor === Array) { - value = value.join(','); - } - - if (value && typeof value === 'object' && value.constructor === Object) { - const valueKeys = Object.keys(value); - for (let j = 0; j < valueKeys.length; j++) { - let v: any = value[valueKeys[j]]; + let value = data[keys[i]]; - if (v && typeof v === 'object' && v.constructor === Array) { - v = v.join(','); - } + if (isObject(value)) { + const valueKeys = Object.keys(value); + for (let j = 0; j < valueKeys.length; j++) { + let v = value[valueKeys[j]]; - query.push(`${encodeURIComponent(`${keys[i]}[${valueKeys[j]}]`)}=${encodeURIComponent(v)}`); + if (Array.isArray(v)) { + v = v.join(','); } - continue; + query.push(`${encodeURIComponent(`${keys[i]}[${valueKeys[j]}]`)}=${encodeURIComponent(v)}`); } - // Encode each key and value, concatenate them into a string, and push them to the array - query.push(`${encodeURIComponent(keys[i])}=${encodeURIComponent(value)}`); + continue; } + + if (Array.isArray(value)) { + value = value.join(','); + } + + // Encode each key and value, concatenate them into a string, and push them to the array + query.push(`${encodeURIComponent(keys[i])}=${encodeURIComponent(value)}`); } // Join each item in the array with a `&` and return the resulting string