Using Map Reduce to Parse Query Strings
So I am using React Router v4 in my project and came to realise that I can no longer access query parameters via the react router v4 api. In previous versions, I’d be able to access them using —
location.query
But now, the react router api only gives us the entire query string as an unparsed string. -
location.search
It is upto us to parse the query string. I was expecting query string parsing to be a core part of the router library. But apparently, they dropped query string parsing for a reason. Fair enough. Now I had to write my own query string parser. Didn’t want to spend too much time on it and did not want to make it overly generic. So I ended up writing a pretty simple map-reduce to parse the query string into an object of query params. Here goes —
export const parseQueryString = (string) => {
return string.slice(1).split("&")
.map((queryParam) => {
let kvp = queryParam.split("=")
return { key: kvp[0], value: kvp[1] }
})
.reduce((query, kvp) => {
query[kvp.key] = kvp.value
return query
}, {})
}// location.search = "?date=2017-05-22×lot=13:00"
// queryParams = parseQueryString(location.search)
// queryParams = { date: "2017-05-22", timeslot: "13:00" }