2

I have a string that has parameters separated with ampersands , for example :

orderid=55e3a83e&DealId=545435&Amount=590 ....

How can I convert that into a Key/Value Map ?

My current code is as follows :

  const text = "orderid=55e3a83e&DealId=545435&Amount=590 ...."


      let _key = "";
      let _value = "";

      var myregexp = /([^&=]+)=(.*?)(?=&[^&=]+=|$)/g;
      var match = myregexp.exec(text);
      while (match != null && key !== "url") {
        _key = match[1];
        _value = match[2];
        dict.push({
          key: _key,
          value: _value
        });
        match = myregexp.exec(subject);
      }

But it's too long , any idea for something better or shorter ?

JAN
  • 21,236
  • 66
  • 181
  • 318
  • The answers from CodeManiac are great, but you do need to consider whether you will support more complex query strings. Many places pass arrays in the query by repeating a key, for instance, "foo=1&bar=2&bar=3&bar=4", which should return a value for `bar` of `[2, 3, 4]`. Most simple techniques won't handle that. But then again, you may not need to. – Scott Sauyet Nov 05 '19 at 17:10
  • Does this answer your question? [Convert URL parameters to a JavaScript object](https://stackoverflow.com/questions/8648892/convert-url-parameters-to-a-javascript-object) – Heretic Monkey Nov 05 '19 at 17:18

3 Answers3

4

You can split first by & and then split each element by =, and build a key/value pair

let mapper = (str) => str.split('&').filter(Boolean).map(v => {
  let [key, value] = v.split('=')
  return { key, value }
})
console.log(mapper('orderid=55e3a83e&DealId=545435&Amount=590 '))

In case desired output in the form of a single object

let mapper = (str) => {
  let splitted = str.split('&').map(v => v && v.split('=')).filter(Boolean)
  return Object.fromEntries(splitted)
}

console.log(mapper('orderid=55e3a83e&DealId=545435&Amount=590 '))
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
  • So the return value is an object and not a dictionary ? – JAN Nov 05 '19 at 17:00
  • How can I grab a value from the dictionary ? I've tried `dict['key']` but it doesn't produce any value.Thanks – JAN Nov 05 '19 at 18:42
  • @JAN you need to use find method, [`find`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) – Code Maniac Nov 06 '19 at 04:35
0

I've always used some code very similar to your current solution:

function getUrlParams(input) {
    var params = {};
    input.replace(/[?&]+([^=&]+)=([^&]*)/g, (m, key, value) => {
            params[key] = value;
        });
    return params;
}

Of course, this doesn't ignore the URL parameter, and it returns a plain JS object... but you get the idea.

SteveR
  • 1,015
  • 8
  • 12
0

The string looks like a URL query, you can use URLSearchParams to parse it, here is an example:

const usp = new URLSearchParams('orderid=55e3a83e&DealId=545435&Amount=590');

const dictionary = [];

for (const [key, value] of usp.entries()) {
  dictionary.push({ key, value})
}

console.log(dictionary);
Titus
  • 22,031
  • 1
  • 23
  • 33