2

How to transform "t=1&m=6&r=2" to {t:1, m:6, r:2} by lodash?

0

3 Answers 3

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>

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.