Last active
April 4, 2020 19:46
-
-
Save 3ch01c/37b7a292c744628f189eeabc917a309b to your computer and use it in GitHub Desktop.
Non-standard URLSearchParams generator functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Inspired by https://gist.github.com/TravelingTechGuy/32454b95a50d296912b9