How to transform "t=1&m=6&r=2" to {t:1, m:6, r:2} by lodash?
3 Answers
You could split the string and use _.fromPairs for getting an object.
If necessary you might use decodeURI for decoding the string with elements like %20.
var string = decodeURI("t=1&m=6&r=%20"),
object = _.fromPairs(string.split('&').map(s => s.split('=')));
console.log(object);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
Comments
Try with simple javascript using split() and Array#reduce() function
var str = 't=1&m=6&r=2';
var res = str.trim().split('&').reduce(function(a, b) {
var i = b.split('=');
a[i[0]] = i[1];
return a;
}, {})
console.log(res)
using lodash
var str = 't=1&m=6&r=2';
var res = _.reduce(_.split(str.trim(),'&'),function(a, b) {
var i = b.split('=');
a[i[0]] = i[1];
return a;
}, {})
console.log(res)
<script src="https://cdn.jsdelivr.net/lodash/4/lodash.min.js"></script>
Comments
If you're working in a browser, you can use the URLSearchParams class. It's not part of lodash, it's just part of standard JavaScript. It's not supported in IE yet, but you can use a polyfill.