How can I parse URL string using only lodash functions without any callbacks inside?
Ex.
var rawUrl = “?a=b454&c=dhjjh&f=g6hksdfjlksd..”
My current solution is
var answer = _.reduce(_.split(_.replace(rawUrl,'?',''), '&'), function(result, ev) {
(result[ev.split('=')[0]] || (result[ev.split('=')[0]] = [])).push(ev.split('=')[1]);
return result;
}, {});
But still, one callback is present here.
I'm aware that you asked for a lodash solution, but maybe people who read the question might also want to look at URLSearchParams, it helped me using less code than the ES6 approach, and avoiding lodash.
const params = new URLSearchParams(window.location.search);
to access a query parameter called 'a'
let a = params.get('a');
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
to avoid callback use _.partial
, _.partialRight
and other lodash methods to work with functions
_.chain(rawUrl)
.replace('?', '') // a=b454&c=dhjjh&f=g6hksdfjlksd
.split('&') // ["a=b454","c=dhjjh","f=g6hksdfjlksd"]
.map(_.partial(_.split, _, '=', 2)) // [["a","b454"],["c","dhjjh"],["f","g6hksdfjlksd"]]
.fromPairs() // {"a":"b454","c":"dhjjh","f":"g6hksdfjlksd"}
.value()
Es6 way without lodash :
const urlParsed =
rawUrl.substring(rawUrl.indexOf("?") + 1)
.split("&")
.reduce(
(memo, param) => ({
...memo,
[param.split("=")[0]]: param.split("=")[1]
}),
{}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With