Parsing URL params
Last updated:
Lets say we want to parse the GET params of an URL with a long list of params into an object for easy consumption. The built-in URLSearchParams() function gives us an iterator of all params in [key, value] arrays, which is efficient, but for legibility it is probably a better idea to convert them into a simple lookup object.
Example URL
https://foo.bar/data?limit=35&offset=0&sort=-updated_at&fields=id,versionTo get structured params we can use URL() and URLSearchParams()
const url = new URL(s)const urlParams = new URLSearchParams(url.search)This gives us an iterator at params.entries(), with [key, value] arrays as entries.
const paramArray = Array.from(urlParams.entries())[ [ "limit", "35" ], [ "offset", "0" ], [ "sort", "-updated_at" ], [ "fields", "id,version" ]]Lets assume the params have no duplicate keys. We can parse these arrays into a more accessible object:
const arrayObjects = paramArray.map(([key, value]) => ({[key]: value}))const params = Object.assign({}, ...arrayObjects){ "limit": "35", "offset": "0", "sort": "-updated_at", "fields": "id,version"}