How to transform "t=1&m=6&r=2"
to {t:1, m:6, r:2}
by lodash?
Asked
Active
Viewed 6,258 times
2

Paul Fitzgerald
- 11,770
- 4
- 42
- 54

David Henry
- 101
- 1
- 7
3 Answers
4
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>

Nina Scholz
- 376,160
- 25
- 347
- 392
2
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>

prasanth
- 22,145
- 4
- 29
- 53
1
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.

Horia Coman
- 8,681
- 2
- 23
- 25