How to transform "t=1&m=6&r=2" to {t:1, m:6, r:2} by lodash?
Asked
Active
Viewed 4,991 times
2
Paul Fitzgerald
- 10,773
- 3
- 38
- 53
David Henry
- 101
- 1
- 6
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
- 351,820
- 24
- 303
- 358
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,442
- 2
- 21
- 25
1
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
- 21,342
- 4
- 27
- 50