Skip to content

Instantly share code, notes, and snippets.

@JTBrinkmann
Last active November 1, 2021 10:03
Show Gist options
  • Save JTBrinkmann/36453f2406ce1e5083e643f0fb7312c2 to your computer and use it in GitHub Desktop.
Save JTBrinkmann/36453f2406ce1e5083e643f0fb7312c2 to your computer and use it in GitHub Desktop.
javascript parse URL search params or FormData as an object
// convert WITHOUT considering multiple values
// every value will be a string
const parseSearchParams = (data) => [...new URLSearchParams(data).entries()].reduce((acc,[key, val]) => (acc[key]=val,acc), {})
// convert WITH considering multiple values
// every value will be a either a string or an array of strings
const parseSearchParamsMultiple = (data) => [...new URLSearchParams(data)].reduce((acc,[key, val]) => (acc[key] = acc[key]?[].concat(acc[key], val) : val, acc), {})
// test cases
const testSingle = "a=1&b=2&c=3"
const testMultiple = "a=1&b=2&c=3&c=4"
const testFormData = new FormData()
testFormData.set("a", 1); testFormData.set("b", 2); testFormData.set("c", 3); testFormData.append("c", 4);
parseSearchParams(testSingle) //=> { a: "1", b: "2", c: "3" }
parseSearchParams(testMultiple) //=> { a: "1", b: "2", c: "4" } (note the c=3 getting silently swallowed)
parseSearchParams(testFormData) //=> { a: "1", b: "2", c: "4" } (note the c=3 getting silently swallowed)
parseSearchParamsMultiple(testSingle) //=> { a: "1", b: "2", c: "3" } (same as before)
parseSearchParamsMultiple(testMultiple) //=> { a: "1", b: "2", c: ["3", "4"] }
parseSearchParamsMultiple(testFormData) //=> { a: "1", b: "2", c: ["3", "4"] }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment