Skip to content

Instantly share code, notes, and snippets.

@3ch01c
Last active April 4, 2020 19:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 3ch01c/37b7a292c744628f189eeabc917a309b to your computer and use it in GitHub Desktop.
Save 3ch01c/37b7a292c744628f189eeabc917a309b to your computer and use it in GitHub Desktop.
Non-standard URLSearchParams generator functions
'use strict'
// Other ways APIs implement URLSearchParams. Not my own, but I can't find the original source.
// https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams
var obj = {
a: 1,
b: 2,
c: [3, 4, 5, null, 7],
foo: {bar: 'baz'}
};
function URLSearchParamsWithArrayBrackets(obj, prefix) {
let str = [],
p;
for (p in obj) {
if (obj.hasOwnProperty(p)) {
let k = prefix ? prefix + "[]" : p,
v = obj[p];
str.push(
v !== null && typeof v === "object"
? URLSearchParamsWithArrayBrackets(v, k)
: encodeURIComponent(k) + "=" + encodeURIComponent(v)
);
}
}
return str.join("&");
}
function URLSearchParamsWithArrayIndices(obj, prefix) {
let str = [],
p;
for (p in obj) {
if (obj.hasOwnProperty(p)) {
let k = prefix ? prefix + "[" + p + "]" : p,
v = obj[p];
str.push(
v !== null && typeof v === "object"
? URLSearchParamsWithArrayIndices(v, k)
: encodeURIComponent(k) + "=" + encodeURIComponent(v)
);
}
}
return str.join("&");
}
var params;
params = new URLSearchParams(obj).toString(); // 'a=1&b=2&c=3%2C4%2C5%2C%2C7&foo=%5Bobject+Object%5D'
params = URLSearchParamsWithArrayBrackets(obj); // 'a=1&b=2&c%5B%5D=3&c%5B%5D=4&c%5B%5D=5&c%5B%5D=null&c%5B%5D=7&foo%5B%5D=baz'
params = URLSearchParamsWithArrayIndices(obj); // 'a=1&b=2&c%5B0%5D=3&c%5B1%5D=4&c%5B2%5D=5&c%5B3%5D=null&c%5B4%5D=7&foo%5Bbar%5D=baz'
@3ch01c
Copy link
Author

3ch01c commented Apr 4, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment